VB.net Lambda運算式使用時機

摘要:VB.net Lambda運算式使用時機

Lambda運算式使用時機

Lambda運算式的使用時機是用在將某部分功能抽離出來,供後續使用者撰寫時決定

List集合提供了一個名為Sort的方法,該方法的功能就是可以提供排序功能,但可惜的是預設的Sort方法只能排序Visual Basic內建的型別,

自訂型別無法使用,以下新增一個自訂型別Employee,並依類別的ID排序

 

Class Employee
    Public ID As Integer
    Public Name As String
End Class


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    Dim empArray As New List(Of Employee) From
        {New Employee() With {.ID = 2, .Name = "Tony"},
        New Employee() With {.ID = 1, .Name = "a"},
        New Employee() With {.ID = 4, .Name = "b"},
        New Employee() With {.ID = 3, .Name = "c"}}
    empArray.Sort(Function(x As Employee, y As Employee) x.ID - y.ID)
    For Each item As Employee In empArray
        Console.WriteLine(item.ID & "__" & item.Name)
    Next
End Sub


如有錯誤 歡迎指正