Lambda Expressions

jamie_pattison

Well-known member
Joined
Sep 9, 2008
Messages
116
Programming Experience
Beginner
Has anyone used Lambda expressions? If so im looking for a simple example to see how i could use them. I have read a few examples on the internet but fail to see what advantage it gives. If anyone can, i would prefer to have an example of what i could do without Lambda and one with Lambda to get a clear understanding.

Thanks
 
A lambda expression is basically an inline method. They don't actually allow you to do anything that you couldn't do without them but they do make your code more succinct. Let's say that you want to sort a String array using the Array.Sort method. One way to do that is with a Comparison(Of String) delegate, which is a reference to a method that takes two Strings as arguments and returns an Integer to indicate their relative order. The first thing you need is a method that does that:
Private Function CompareStrings(s1 As String, s2 As String) As Integer
    Return s1.CompareTo(s2)
End Function
You can then make use of that method to sort an array like this:
Array.Sort(arr, New Comparison(Of String)(AddressOf CompareStrings))
You can do away with the CompareStrings method altogether though, and use a lambda expression in that second code snippet instead:
Array.Sort(arr, Function(s1, s2) s1.CompareTo(s2))
Have a close look at that lambda expression and now have another look at the conventional method that does the same thing:
VB.NET:
Private [COLOR="#FF0000"]Function[/COLOR] CompareStrings[COLOR="#FF0000"](s1[/COLOR] As String, [COLOR="#FF0000"]s2[/COLOR] As String[COLOR="#FF0000"])[/COLOR] As Integer
    Return [COLOR="#FF0000"]s1.CompareTo(s2)[/COLOR]
End Function
The lambda expression contains all the same required parts of the conventional method and everything else is inferred from the usage.
 
Thanks for that. Its getting a little clearer :).

So correct me if im wrong but i assume this isnt limited to arrays/collections etc? If i had a function such as

VB.NET:
Private Function AddNumbers (Byval num1 as integer, byval num2 as integer) as Integer
Return num1 + num2
End Function

Therefore a Lambda expression could be

VB.NET:
Dim AddNumbers As Integer

AddNumbers = (Function(num1,num2) num1 + num2)

Looks a little wrong but i suspect im still missing a piece of this puzzle.

Thanks again
 
That's not useful because where are 'num1' and 'num2' supposed to come from? A lambda expression results in a delegate. You wouldn't use a lambda expression anywhere that you wouldn't use a delegate referring to a conventional method. It's a bit of a contrived example but you could use an lambda like that in this way:
Dim adder As Func(Of Integer, Integer, Integer) = Function(i1, i2) i1 + i2

Dim result1 = adder(10, 20)
Dim result2 = adder(50, 100)
That declares a Func delegate and assigns a lambda to it. That delegate can then be invoked much like a conventional method, passing it two Integers arguments and it returning the result.
 
jmc said:
Dim adder As Func(Of Integer, Integer, Integer) = Function(i1, i2) i1 + i2
You can also infer types other way around, like this:
Dim adder = Function(i1 As Integer, i2 As Integer) i1 + i2

Type inferring is when compiler is 'filling in the blanks' in relation to which type something must be based on something else. The approach in jmcilhinneys example is more common when using extension methods on collections where the type of the elements and other parameters is known, my example is the more common approach when the expression is known and you let compiler infer the type of the resulting object.
jamie_pattison said:
fail to see what advantage lambdas gives
Lambdas can make code for small methods much simpler, including allowing parameter types to be inferred.
Lambdas are typed as delegates, so saves you defining/using those when passing method references as parameters.
 
Hi,

Without being rude to the moderators who have already responded, I do feel that the examples given so far are quite complex for someone trying to get their head round Lambda expressions for the first time.

Here are a couple of other, simple, examples to help you get your head round Lambda expressions. The first calculates the sum of the square of all the values in an array and the second sums all the values in an array where the value is grater than 5.

VB.NET:
Public Class Form1
 
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myIntegers() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
    TextBox1.Text = (myIntegers.Sum(Function(x) x ^ 2)).ToString
  End Sub
 
  Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Dim myIntegers() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
    TextBox1.Text = (myIntegers.Where(Function(x) x > 5).Sum).ToString
  End Sub
End Class

I hope this helps in combination with what has already been provided.

Cheers,

Ian
 
Back
Top