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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With