开发者

How to use .Where in generic list

I have a List(Of MyType) and I would like to use LINQ to get a subset开发者_C百科 of the list.

On MyType there's a field called AccountNumber. Can I use LINQ to say soemthing like this?

Dim t As List(Of MyType)
t = GetMyTypes()
t = t.Where(AccountNumber = "123")

Thanks


You're almost there. The argument of Where needs to be a function, so your code should look like this:

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜