There are two types of lambda expressions the predicate and the projection.
A predicate is a boolean expression that indicates membership of an element in a collection.
Example 3:
public static class AggregationClass
{
public delegate bool Predicate<T>(T a);
public static IEnumerable<T> PredicateMethod<T>(this IEnumerable<T> data, Predicate<T> func)
{
foreach (var el in data)
{
if (func(el))
yield return el;
}
}
}
class Program
{
static void Main(string[] args)
{
string[] array = new[] { "ab", "abc", "ac" };
foreach (var item in array.PredicateMethod(a => a == "ab" || a == "abc"))
{
Trace.WriteLine(item);
}
}
}
Output:
ab
abc
A projection is a lambda expression that returns a type different from the type of a given single parameter.
Example 4:
public static class AggregationClass
{
public delegate T1 Projection<T1, T2>(T2 a);
public static IEnumerable<T1> ProjectionMethod<T1, T2>(this IEnumerable<T2> data, Projection<T1, T2> func)
{
foreach (var el in data)
{
yield return func(el);
}
}
}
class Program
{
static void Main(string[] args)
{
string[] array = new[] { "ab", "abc", "ac" };
foreach (var item in array.ProjectionMethod(a => a.Length))
{
Trace.WriteLine(item);
}
}
}
Output:
2
3
2
The main difference between statements and expressions is that expressions calculate and return the calculated value and don’t change the state of a program environment.
Example 5:
class Program
{
delegate T Func<T>(T a, T b);
static void Main(string[] args)
{
Func<int> func = (a, b) => a – b;
Trace.WriteLine(func.GetType());
Trace.WriteLine(func(3, 2));
Expression<Func<int>> expressionTree = (a, b) => a – b;
Trace.WriteLine(expressionTree.GetType());
//’expressionTree’ is a ‘variable’ but is used like a ‘method’
//Trace.WriteLine(expressionTree(3, 2));
Trace.WriteLine(expressionTree.Compile()(3,2));
Console.ReadKey();
}
}
Output:
LambdaExpressions.Program+Func`1[System.Int32]
1
System.Linq.Expressions.Expression`1[LambdaExpressions.Program+Func`1[System.Int32]]
‘LambdaExpressions.vshost.exe’ (Managed): Loaded ‘Anonymously Hosted DynamicMethods Assembly’
1
The main difference between delegates and expression trees is that delegates compiled by the C# turn into IL code, while expression trees turn into executable code only in runtime. It is useful when we need to convert one piece of code to another, for example from LINQ statements to SQL statements.