Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0371 Lambda and Linq

Most query operators accept a lambda expression as an argument. using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] names = { "C", "Java", "C#", "Javascript" }; IEnumerable<string> filteredNames = System.Linq.Enumerable.Where(names, n => n.Length >= 4); foreach (string n in filteredNames) Console.WriteLine(n); } } The output: Java Javascript In example above, the lambda expression is as follows: n => n.Length >= 4 The input argument corresponds to an input element. n represents each name in the array and is of type string. The Where operator requires that the lambda expression return a bool value, which if true, indicates that the element should be included in the output sequence. Here's its signature: public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate) The following query retrieves all names that contain the letter "a": using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] names = { "C", "Java", "C#", "Javascript" }; IEnumerable<string> filteredNames = names.Where(n => n.Contains("a")); foreach (string name in filteredNames) Console.WriteLine(name); } } The output: Java Javascript