Monday, December 3, 2012

LINQ Operators: Projection Operators

In previous article we discussed about Filtering operators in LINQ. So moving forward today we will see the Projection Operators in LINQ



Projection Operators


LINQ has two projection operators namely Select and SelectMany.
  1. Select- Just like Select in SQL, Select operator returns specified elements. Select operator returns one output element for each input element. The record or data retrieval based on two models. One is element based selection and another one is Index based selection.
    Index based:
    int[] digits = { 1, 5, 6, 2, 0 };
    string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
    var textNums = from n in digits
                   select strings[n]; /*one five six two zero*/

    Element based:
    string[] strings = { "zero", "one", "two", "three" };

    var query= from s in strings

               select s; /*zero one two three*/ 
  2. SelectMany- The SelectMany operator is useful when you are working on sequence of sequences. SelectMany concatenates sub sequences into a single flat output sequence. The SQL equivalent of SelectMany is INNER JOIN, LEFT OUTER JOIN and CROSS JOIN. 
       string[] famousQuotes = {"Advertising is legalized lying",
    "Advertising is the greatest art form of the twentieth century"};
    var query =   famousQuotes.SelectMany(s => s.Split(' ')).Distinct();
      
    /*Output
    Advertising
    is
    legalized
    lying
    the
    greatest
    art
    form
    of
    twentieth
    century
    */

To be continude.....
Happy reading!!

 

No comments:

Post a Comment

^ Scroll to Top