21

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

Heinzi
  • 167,459
  • 57
  • 363
  • 519
Tigran
  • 872
  • 1
  • 9
  • 25

1 Answers1

39

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Not sure if it's okay to add to this... Wouldn't adding a .First to the .Where() make this a bit better? – Feign Oct 31 '14 at 18:37
  • 2
    @Feign: It really depends on what you want to achieve: If you want the **first** entry with account number `123`, use `First` (adding an `Order By` clause might be useful in that case, though). If you want **a list of all** entries with account number `123` , use `ToList`. – Heinzi Oct 31 '14 at 22:36