Lambda expressions available in the new C# 3.0 compiler are mostly used in the context of LINQ queries, like this:
internal class Product {
internal int ID { get; set; }
}

var products = new List<Product>();
products.Add(new Product() { ID = 1 });
products.Add(new Product() { ID = 5 });
// continue to fill in products
var one1 = from p in products where p.ID == 1 select p;

It’s not obvious, but the above query is equivalent to (also note that one1’s type is IEnumerable<Product>, not Product):

var one2 = products.Where(p => p.ID == 1);

The part p => p.ID == 1 is the lambda expression and in this case (lambdas are more general than a simple delegate substitute) can be substituted by a C# 2.0 feature called anonymous delegate:

var one3 = products.Where(delegate(Product p) { return p.ID == 1; });

One advantage of lambdas is already obvious: we didn't have to specify the type of the parameter of the delegate, plus there was no need to type return. To a certain extent, this is actually a feature of the new compiler (better type inference), but it does not work in all cases (it can’t), so sometimes (not here, but works nevertheless) you must qualify the parameter with a type, like this:

var one4 = products.Where((Product p) => p.ID == 1);

It is relatively easy to conclude from this that the syntax for lambdas with no parameters is likely:

() => /* some criteria, note that parenthesis are required */

This is probably obvious to many developers (especially those using the help files and not deducing things like this), but the reason I mention it here is I've seen many LINQ articles that use anonymous delegates as if the author did not know that lambdas can have no parameters too. For completion, here's how a syntax of an anonymous delegate with no parameters looks like:

delegate { /* statements */ }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments