Subqueries in LINQ

Definition:- In Linq, subquery is a query which can be contained within another query's 
                             lambda expression.

The following example can help in understanding the subquery concept in Linq. 

Examples:-

I will be using the four different ways to achieve the same output to showcase the flexibility and richness of LINQ.

In the following examples the query will return all the string values from the array whose length matches with the length of shortest string. 

Option 1:-

string[] inSequence = { "london", "new york", "sydney", "new delhi" };

var outSequence = inSequence.Where(n => n.Length == 
                                      inSequence.OrderBy(n2 =>n2.Length).Select(n2 => n2.Length).First());

foreach (string strTemp in outSequence)
             Console.WriteLine(strTemp);

Output
-------
london 
sydney

Option 2:-

string[] inSequence = { "london""new york""sydney""new delhi" };


var outSequence= from n in inSequence
                                where n.Length == (from n2 in inSequence
                                                                    orderby n2.Length
                                                                    select n2.Length).First()
                                select n;

foreach (string strTemp in outputSequence1)
         Console.WriteLine(strTemp);

Output
-------
london 
sydney

Option 3:-

string[] inSequence = { "london""new york""sydney""new delhi" };

var outSequence = from n in inSequence
                                  where n.Length == inSequence.OrderBy(n2=>n2.Length).First().Length
                                  select n;

foreach (string strTemp in outSequence)
               Console.WriteLine(strTemp);

Output
-------
london 
sydney

Option 4:-

string[] inSequence = { "london""new york""sydney""new delhi" };

var outSequence = from n in inSequence
                                  where n.Length == inSequence.Min().Length
                                  select n;

foreach (string strTemp in outSequence)
               Console.WriteLine(strTemp);

Output
-------
london 
sydney

As it can be seen from the above examples, the same output has been achieved using four different query patterns. 


This is the richness of LINQ, that a requirement can be fulfilled using different ways and purely depends on individuals, which path or way they want to take for achieving theirs goals.

Happy Coding...........

Comments