Monday, July 15, 2013

LINQ 11- Filtering with Where Clause

One of the important operation in list of values is filtering. in LINQ filtering can be done with where clause or Where extension method.

 

Where clause receives value of each element and needs an expression that returns a boolean value based on the input element. Result will be the list of elements which results true while evaluating the where clause.

 

Sample 1

Extension Method

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Where(number => number > 2);

LINQ

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected =

    from number in numbers where number > 2 select number;

Sample 2

Extension Method

IEnumerable<Employee> managers = employees.Where(employee => employee.Role==”Manager”);

LINQ

IEnumerable<Employee> managers =

    from employee in employees

    where employee.Role==”Manager”

    select employee;

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

Sunday, July 07, 2013

LINQ 10- Projection/Select- 3

Lazy loading

Linq does few things in background for better performance. One of the important thing is lazy loading. Linq statements or methods are not executed immediately in the very statement. To verify this we can use the following sample class.

public class Employee {
    private string name;
    public string Name {
        get {
            Console.WriteLine("Name Get ");
            return name;
        }
        set {
            name = value;
        }
    }
}

 

In the above code, whenever the Employee name is retrieved it will print the message “Name Get” in the console.

Following code uses the above Employee class for LINQ.

Employee[] employees = new Employee[] {
    new Employee { Name = "John" },
    new Employee { Name = "Bill" },
    new Employee { Name = "Steve" } };
IEnumerable<String> selected = employees.Select(employee => employee.Name);

foreach (String item in selected)
    Console.WriteLine(item);

 

  • In the first statement, we have declared 3 Employees.
  • In the second statement, employee.Name is retrieved from the collection. If the Select method has completed its work in that statement itself, it will get all 3 names and it should print 3 “Name Get” messages. But, it will not, as it is just stores, what needs to be done and not actually doing it.
  • Next, the for each statement prints each names. Meanwhile, to print the names, names should be retrieved from the previous statement. But due to lazy loading,  names are retrieved during MoveNext method’s execution (implicitly done in foreach statement)

Output will be

Name Get
John
Name Get
Bill
Name Get
Steve

Above output clearly shows the Select is not immediately executed.

 

If we print the Type name of “selected” variable, we can see how this is done.

We can use the following statement to check this.

Console.WriteLine(selected.GetType().FullName);

Output

System.Linq.Enumerable+WhereSelectArrayIterator`2[Employee, String]

So during the execution .Net stores the transformation information in the WhereSelectArrayIterator.

WhereSelectArrayIterator class is an internal class, so cannot see the details using Object Browser, but, we can see the details using reflection. We can see this in further posts.

 

We can force the execution of LINQ statements to complete using some other LINQ extensions. Some of them are,

  • ToArray
  • ToList
  • Count

Example

Employee[] employees = new Employee[] {
    new Employee { Name = "John" },
    new Employee { Name = "Bill" },
    new Employee { Name = "Steve" } };
List<String> selected = employees.Select(employee => employee.Name).ToList();

foreach (String item in selected)
    Console.WriteLine(item);

Output

Name Get
Name Get
Name Get
John
Bill
Steve

Tuesday, July 02, 2013

LINQ 10- Projection/Select- 2

IEnumerable’s extension method Select, automatically identifies the input and output type. Input and output types are not restricted.

So Select method is powerful enough to transform one object to another. We already have seen one example in  “LINQ 10- Projection/Select- 1” which transforms an integer array to string Enumerable.

 

Following statement extracts the Name from Employee object.

IEnumerable<String> selected = employees.Select(employee => empoyee.Name);

 

Here Employees is the source IEnumerable witch generic type argument Employee. So TSource is Employee.

Transformation function gets the Name from Employee and returns it. So TResult is String.

 

Even we can transform a class object to another class object

IEnumerable<Manager> selected = employees.Select(employee => new Manager() {
    ID = employee.ID,
    Name =  employee.Name
});

 

Above statement transforms a list of Employee objects to List of Manager Objects