使用lambda表达式时,有没有更好的方法在.NET中过滤泛型集合?注重可读性,但在使用lambda表达式或LINQ时,请避免使用不必要的代码并遵循最佳实践。
以下是一些过滤包含Pet类型对象的泛型集合的代码,我们希望使用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
答案 0 :(得分:2)
如果你想在VB中使这个更惯用(并且更简洁),你可以使用Aggregate子句如下:
Dim minAge = Aggregate p In pets Where p.PetType = "Dog" Into Min(p.Age)
答案 1 :(得分:1)
效率不高,但略短,希望更具可读性:
Dim min As Integer =
(From pet In pets Where pet.PetType = "Dog" Select pet.Age).Min
我只是将你的内联LINQ转换为查询样式。