vb.net 如何使用 .Where 在通用列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4197899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use .Where in generic list
提问by Tigran
I have a List(Of MyType) and I would like to use LINQ to get a subset of the list.
我有一个 List(Of MyType) 并且我想使用 LINQ 来获取列表的一个子集。
On MyType there's a field called AccountNumber. Can I use LINQ to say soemthing like this?
在 MyType 上有一个名为 AccountNumber 的字段。我可以用 LINQ 说这样的话吗?
Dim t As List(Of MyType)
t = GetMyTypes()
t = t.Where(AccountNumber = "123")
Thanks
谢谢
回答by Heinzi
You're almost there. The argument of Where
needs to be a function, so your code should look like this:
您快到了。的参数Where
需要是一个函数,所以你的代码应该是这样的:
Dim t As List(Of MyType)
t = GetMyTypes()
Dim result = t.Where(Function(x) x.AccountNumber = "123")
Alternatively, you can use the verbose LINQ syntax:
或者,您可以使用详细的 LINQ 语法:
Dim result = From t In GetMyTypes() Where t.AccountNumber = "123"
The data type returned is not a List(Of MyType)
but an IEnumerable(Of MyType)
, so you cannot directly assign it to a variable declared as List(Of MyType)
. If you want to create a list, you can "convert" it by using result.ToList()
. This would also cause the list to be evaluated immediately.
返回的数据类型不是 aList(Of MyType)
而是 an IEnumerable(Of MyType)
,因此您不能将其直接分配给声明为 的变量List(Of MyType)
。如果要创建列表,可以使用result.ToList()
. 这也将导致立即评估列表。