Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0375 Lambda expressions and Func signatures

The standard query operators utilize generic Func delegates. Func<TSource,bool> matches a TSource=>bool lambda expression: one that accepts a TSource argument and returns a bool value. Similarly, Func<TSource,TResult> matches a TSource=>TResult lambda expression. The signature of the Select query operator: public static IEnumerable<TResult> Select<TSource,TResult> (this IEnumerable<TSource> source, Func<TSource,TResult> selector) Func<TSource,TResult> matches a TSource=>TResult lambda expression: one that maps an input element to an output element. TSource and TResult are different types. The following query uses Select to transform string type elements to integer type elements: using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] names = { "C", "Java", "C#", "Javascript" }; IEnumerable<int> query = names.Select(n => n.Length); foreach (int length in query) Console.Write(length + "|"); } } The output: 1|4|2|10| Here is the Where query operator method signature. public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate)