Lambda coding

iknowyou

Active member
Joined
Jun 14, 2011
Messages
37
Programming Experience
1-3
Im hearing about this, can someone explain it to me or please show some basic code of Lambda with explanation. Sorry Im newbie :eek:.
 
A lambda expression is basically an inline function. It provides a succinct way to create a delegate to method. For instance, consider a list of Person objects that you want to sort by LastName. Without a lambda expression, that might look like this:
VB.NET:
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim people As New List(Of Person)

        people.Add(New Person With {.FirstName = "Mary", .LastName = "Smith"})
        people.Add(New Person With {.FirstName = "John", .LastName = "Smith"})
        people.Add(New Person With {.FirstName = "Bill", .LastName = "Jones"})

        people.Sort(AddressOf ComparePeopleByLastNameThenFirstName)

        For Each person In people
            MessageBox.Show(person.FirstName, person.LastName)
        Next
    End Sub

    Private [COLOR="#FF0000"]Function[/COLOR] ComparePeopleByLastNameThenFirstName([COLOR="#FF0000"]person1[/COLOR] As Person, [COLOR="#FF0000"]person2[/COLOR] As Person) As Integer
        Return [COLOR="#FF0000"]person1.LastName.CompareTo(person2.LastName)[/COLOR]
    End Function
End Class


Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class
In this case, we use AddressOf to create a delegate for the ComparePeopleByLastNameThenFirstName function, which the Sort method then uses to compare pairs of items in order to sort them. Here's how that might look using a lambda expression:
VB.NET:
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim people As New List(Of Person)

        people.Add(New Person With {.FirstName = "Mary", .LastName = "Smith"})
        people.Add(New Person With {.FirstName = "John", .LastName = "Smith"})
        people.Add(New Person With {.FirstName = "Bill", .LastName = "Jones"})

        people.Sort([COLOR="#FF0000"]Function[/COLOR]([COLOR="#FF0000"]person1[/COLOR], [COLOR="#FF0000"]person2[/COLOR]) [COLOR="#FF0000"]person1.LastName.CompareTo(person2.LastName)[/COLOR])

        For Each person In people
            MessageBox.Show(person.FirstName, person.LastName)
        Next
    End Sub
End Class


Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class
Note the highlighted portions of each code snippet, showing how the lambda expression is equivalent to the normal named method. All the bits missing from the first code snippet are inferred by the compiler, e.g. it knows that 'person1' and 'person2' are type Person because the list being sorted is a List(Of Person).
 
Back
Top