Lambda Expressions

The standard query operators are implemented as extension methods we can call them directly, as though they were instance methods.


string[] words = { "one", "four",  "seven" }; 
IEnumerable<string> filteredWords = words.Where (n => n.Length >= 4);


Most query operators accept a lambda expression as an argument


The following query extracts all words that contain the letter "o".

IEnumerable<string> filteredWords = words.Where (n => n.Contains("o") ); 

Where, OrderBy, Select are standard query operators that resolve to extension methods in the Enumerable class



Extension Methods with Chaining

string[] words = { "one", "two", "three", "four", "six", "seven" }; 

IEnumerable<string> query = words
   .Where (n => n.Contains("o"))
   .OrderBy (n => n.Length)
   .Select (n => n.ToUpper());

Extension Methods without Chaining

IEnumerable<string> filter = words   .Where    (n => n.Contains("o")) 
IEnumerable<string> sorted = filter .OrderBy (n => n.Length);
IEnumerable<string> result = sorted .Select (n => n.ToUpper());

No Extension Methods with Chaining

IEnumerable<string> filter = 
  Enumerable.Select (
    Enumerable.OrderBy (
      Enumerable.Where (
        words, n => n.Contains("o")
      ), n => n.Length
    ), n => n.ToUpper()
  );

No Extension Methods without Chaining

IEnumerable<string> filter = Enumerable.Where    (words, n => n.Contains("o")); 
IEnumerable<string> sorted = Enumerable.OrderBy (filter, n => n.Length)
IEnumerable<string> result = Enumerable.Select (sorted, n => n.ToUpper());


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext