Browse DevX
Sign up for e-mail newsletters from DevX


From Delegate to Lambda : Page 4

The key to understanding lambda expressions lies in understanding delegates.





LINQ and Lambdas
Lambda expressions are a short, concise way of defining delegates. You use lambda expressions a lot in LINQ. The vast majority of LINQ methods use delegates to allow you to sort, filter, project, and take action on collections of objects. LINQ adds all these functions to existing collections by implementing them as extension methods to IEnumerable (in C#), or IEnumerable(Of T) (in VB). With the code that you've written so far, you're only two steps away from creating your own mini-LINQ. If you move the Select method into a public static class and make it public then you can turn it into an extension method:

// In C#: public static List<int> Select( this List<int> numbers, Filter filter ) { List<int> result = new List<int>(); foreach ( int i in numbers ) { if ( filter( i ) == true ) { // call delegate result.Add( i ); } } return result; } // call extension method List<int> even = _numbers.Select( x => x % 2 == 0 ); ' in VB: Imports System.Runtime.CompilerServices Module MiniLINQ <Extension()> _ Public Function [Select]( _ ByVal numbers As List(Of Integer), _ ByVal filter As Filter) _ As List(Of Integer) Dim result As New List(Of Integer) For Each number In numbers ' call delegate If filter(number) = True Then result.Add(number) End If Next Return result End Function End Module ' call extension method Dim even = _ _numbers.Select(Function(x) x Mod 2 = 0)

The code above looks extremely similar to what it will look like when you use the LINQ extensions. Of course, the LINQ extensions are much more powerful since they are all made to be generic-your extension can deal only with lists of integers, but the concept is exactly the same.

In this article, you've seen how delegates can help implement generic functionality. The use of delegates has grown as the .NET Framework and .NET Runtime has grown; from a first implementation to anonymous methods, we have now arrived at lambda expressions: a short, concise way of defining delegates.

Mark Blomsma is a software developer, software architect, author, and speaker specializing in Microsoft .NET technologies. He�s been working as an IT professional for more than 14 years and is currently an independent contractor through his company Develop-One (www.develop-one.com). He is a freelance instructor for DevelopMentor and has received the Microsoft MVP for his community contributions five years running.