Monday, September 17, 2007 10:29 AM
kolbis
Lambda Expressions
Visual studio Orcas and C# 3.0 introduce some very cool features. Recently I have been working on several posts that talk about those new features. I recommend you all to review them:
In this post I will be discussing on yet another cool feature: Lambda Expressions.
Overview
C# 2.0 introduced a new feature, anonymous methods, that allows you to declare your method code inline instead of with a delegate function:
FileSystemWatcher watcher = new FileSystemWatcher(@"c:\");
watcher.Changed += delegate(object sender, FileSystemEventArgs e)
{
//do something...
};
As you can see, I did not create a method to handle the Change event, instead I use an inline declaration for the method handler.
Lambda Expressions
An expression is a set of language elements combined to perform a meaningful computation.
C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block. This feature simplifies coding delegates and anonymous methods.
Person p1 = new Person(){ ID = 1, IDRole = 1, FirstName = "guy", LastName = "kolbis" };
//with delegation:
Func<Person, bool> f = p => p.ID == 1;
bool res = f(p1);
In this example, I have created a delegation that gets a Person as input parameter and returns bool. The delegation will check if the Person's ID equals to 1. The delegation is compiled into executable code and we can invoke it later on. As you can see, this is fairly simple.
You can also use the delegation with multi parameters:
Func<Person, Person, bool> f2 = (person1, person2) => person1.LastName == person2.LastName;
res = f2(p1,p2);
You can also query an IEnumerable<T>:
List<Person> people = new List<Person>
{
new Person(){ ID = 1, IDRole = 1, LastName = "Anderson", FirstName = "Brad"},
new Person(){ ID = 2, IDRole = 2, LastName = "Gray", FirstName = "Tom"}
};
people.Where(p => p.ID == 1).Select(p => new { p.FirstName, p.LastName });
Summary
Lambda expressions provide a simple way to write inline code blocks where delegates are expected. Their behavior is strikingly similar to anonymous methods. In fact, they are syntactic sugar in terms of syntax.
תגים:.NET Framework 3.0, Orcas Beta 2, .NET Framework 3.5