Thursday, July 11, 2013

LINQ 10- Projection/Select- 4

LINQ statements are simple like SQL, with minor changes. One of the important change is the Select clause comes later in LINQ. Examples shown in previous posts can be rewritten as follows.

 

Query 1

Extension Method

IEnumerable<int> selected = numbers.Select(number => number);

                            ------- ------ ------    ------

                            Part1   Part2  Part3     Part4

LINQ

IEnumerable<int> selected = from number in numbers select number;

                                 ------    ------- ------ ------

                                 Part3     Part1   Part2  Part4

Query 2

Extension Method

IEnumerable<int> selected = numbers.Select(number => number * 2);

                            ------- ------ ------    ----------

                            Part1   Part2  Part3     Part4

LINQ

IEnumerable<int> selected = from number in numbers select number * 2;

                                 ------    ------- ------ ----------

                                 Part3     Part1   Part2  Part4

Query 3

Extension Method

IEnumerable<string> selected =

    numbers.Select(number => (number * 2).ToString());

    ------- ------ ------    -----------------------

    Part1   Part2  Part3     Part4

LINQ

IEnumerable<string> selected =

    from number in numbers select (number * 2).ToString();

         ------    ------- ------ -----------------------

         Part3     Part1   Part2  Part4

Query 4

Extension Method

IEnumerable<string> selected =

    employees.Select(employee => employee.Name);

    --------- ------ --------    -------------

    Part1     Part2  Part3       Part4

LINQ

IEnumerable<string> selected =

    from employee in employees select employee.Name;

         --------    --------- ------ -------------

         Part3       Part1     Part2  Part4

 

Here the

Part1 is the source on which the LINQ is to be executed

Part2 is the operation to be executed, here the transformation

Part3 is the alias name to be used for each item in the source

Part4 is the transformation to be applied, it can be any complex expression returning a single value

No comments:

Post a Comment