Reputation: 3283
Is there any better way to filter a generic collection in .NET when using lambda expressions? Focus on readability but avoiding unnecessary code and following best practices when using lambda expressions or perhaps LINQ.
Here is some code for filtering a generic collection containing objects of type Pet and we want to get the minimum age of all objects with PetType = "Dog".
Module Module1
Public Class Pet
Public Name As String
Public Age As Integer
Public PetType As String
End Class
Sub Main()
' Create an array of Pet objects.
Dim pets As New List(Of Pet) From {
New Pet With {.Name = "Barley", .Age = 8, .PetType = "Dog"}, _
New Pet With {.Name = "Boots", .Age = 4, .PetType = "Dog"}, _
New Pet With {.Name = "Jacky", .Age = 1, .PetType = "Cat"}, _
New Pet With {.Name = "Whiskers", .Age = 2, .PetType = "Dog"}
}
' Find the youngest dog by passing a
' lambda expression to the Min() method.
Dim min As Integer = pets.Where(Function(pet) pet.PetType = "Dog").Min(Function(pet) pet.Age)
' Display the result.
Console.WriteLine("The youngest dog is age " & min)
' This code produces the following output:
'
' The youngest dog is age 2
Console.ReadLine()
End Sub
End Module
Upvotes: 1
Views: 1629
Reputation: 10398
If you want to make this more idiomatic (and slightly more concise) in VB, you could use the Aggregate clause as follows:
Dim minAge = Aggregate p In pets Where p.PetType = "Dog" Into Min(p.Age)
Upvotes: 2
Reputation: 26424
Not more efficient, but slightly shorter and hopefully more readable:
Dim min As Integer =
(From pet In pets Where pet.PetType = "Dog" Select pet.Age).Min
I merely converted your inline LINQ to query style.
Upvotes: 1