Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .Where in generic list

Tags:

vb.net

linq

I have a List(Of MyType) and I would like to use LINQ to get a subset 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

like image 740
Tigran Avatar asked Nov 16 '10 18:11

Tigran


1 Answers

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.

like image 199
Heinzi Avatar answered Nov 16 '22 23:11

Heinzi