Lambda expressions
With the C# 3.0 new feature extension method and the C# 2.0 new feature anonymous method (or inline method), Visual Studio introduces a new expression called lambda expression.
Lambda expression is actually a syntax change for anonymous methods. It is just a new way of writing anonymous methods. Next, let's explain what a lambda expression is, step by step.
First, in C# 3.0, there is a new generic delegate type, Func<A,R>
, which presents a function taking an argument of type A
and returns a value of type R
:
delegate R Func<A,R> (A Arg);
In fact there are several overloaded versions of Func
of which Func<A,R>
is one.
Now we will use this new generic delegate type to define an extension:
public static IEnumerable<T> Get<T>(this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) { if (predicate(item)) yield return item; } }
This extension method will apply to an object that extends...