Sunday, 12 February 2012

LINQ Operators



Letting a Sub-List



We saw that you can get the result of a LINQ statement from the select section. In reality, the select statement simply indicates that the result is ready and it hands it to the other parts of the program. Instead of getting the result directly from the select statement, you can first store it in a local LINQ variable. This allows you to treat the result as a variable that you can then manipulate before getting the final result.
   
To create a local variable in the LINQ statement, you can use the let operator. You must use it before the select statement to hold the result. 

Here is an example:

var fullNames = from empls
                in employees
                let FullName =  empls.LastName + ", " + empls.FirstName
                select FullName;

foreach (var empl in fullNames)
    Console.WriteLine(empl);
 

If you need a where condition but your let variable would be used only to hold the final result, you can declare that let variable after the where statement. 

Here is an example:

var fullNames = from empls
                in employees
                where empls.LastName == "Mukoko"
                let FullName =  empls.LastName + ", " + empls.FirstName
                select FullName;

foreach (var empl in fullNames)
    Console.WriteLine(empl);
 
 

You can create the let variable before the where statement and you would get the same result: 

var fullNames = from empls
                in employees
                let FullName =  empls.LastName + ", " + empls.FirstName
                where empls.LastName == "Mukoko"
                select FullName;

foreach (var empl in fullNames)
    Console.WriteLine(empl);


Creating a New List



To get the final result of a query, you may want to combine a few fields or properties of the class. For example, as we have seen so far, you may want to combine the last and the first name of each result to create a full name. Besides, or instead of, the let operator, you can use the new operator to create such a combination. 

To use the new operator, after the select keyword, type new followed by an opening "{" and a closing curly "}" brackets. Inside the brackets, create an expression as you see fit and assign it to a local variable in the curly brackets. When accessing the result in your foreach loop, apply the period operator on the foreach variable to access the new local variable(s).

 Here is an example:

var fullNames = from empls
                in employees
                select new { FullName =  empls.LastName + ", " + empls.FirstName };

foreach (var empl in fullNames)
    Console.WriteLine(empl.FullName);
 

To make the statement easier to read, you can span it on various lines:

var fullNames = from empls
                in employees
                select new
                {
                    FullName =  empls.LastName + ", " + empls.FirstName
                };

foreach (var empl in fullNames)
    Console.WriteLine(empl.FullName);
 

One of the most valuable features of the new operator is that it allows you to create a selected query of fields of the members of the class. For example, you cannot use a select statement to select more than one member of the class that holds the value. On the other hand, you can create a new body in which you list the desired members of the class, each member must be qualified using the period operator.

 Here are examples:

var fullNames = from empls
                in employees
                select new
                {
                    empls.EmployeeNumber,
                    empls.LastName
                };


If you want one of the new fields to be a combination of the members of the class, you must create a name for it and assign the expression to it. 

Here is an example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        employees = new Employee[]
        {
            new Employee(971974, "Patricia", "Katts", 24.68M),
            new Employee(208411, "Raymond", "Kouma", 20.15M),
            new Employee(279374, "Hél�ne", "Mukoko", 15.55M),
            new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
            new Employee(971394, "Gertrude", "Monay", 20.55M)
        };

        var staffMembers = from empls
                           in employees
                           select new
                           {
                               empls.EmployeeNumber,
                               FullName = empls.LastName + ", " + empls.FirstName,
                               empls.HourlySalary
                           };

        Console.WriteLine("+========+=====================+========+");
        Console.WriteLine("| Empl # | Full Name           | Salary |");
        foreach (var staff in staffMembers)
        {
            Console.WriteLine("+--------+---------------------+--------+");
            Console.WriteLine("| {0,6} | {1,-19} | {2,6} |", staff.EmployeeNumber,
                staff.FullName, staff.HourlySalary);
        }
        Console.WriteLine("+========+=====================+========+");

        Console.WriteLine();
        return 0;
    }
}

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public decimal HourlySalary;

    public Employee(int number = 0,
                       string firstName = "John",
                       string lastName = "Doe",
                       decimal salary = 0M)
    {
        EmployeeNumber = number;
        FirstName = firstName;
        LastName = lastName;
        HourlySalary = salary;
    }

    internal string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}


This would produce:

New


In the same way, if you want, in the new body, you can create a name for each field and assign it the member of the class that holds the actual fields. 

Here are examples:

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        employees = new Employee[]
        {
            new Employee(971974, "Patricia", "Katts", 24.68M),
            new Employee(208411, "Raymond", "Kouma", 20.15M),
            new Employee(279374, "Hél�ne", "Mukoko", 15.55M),
            new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
            new Employee(971394, "Gertrude", "Monay", 20.55M)
        };

        var staffMembers = from empls
                           in employees
                           select new
                           {
                               Number = empls.EmployeeNumber,
                               FName = empls.FirstName,
                               LName = empls.LastName,
                               Wage = empls.HourlySalary
                           };

        Console.WriteLine("+========+============+===========+========+");
        Console.WriteLine("| Empl # | First Name | Last Name | Salary |");
        foreach (var staff in staffMembers)
        {
            Console.WriteLine("+--------+------------+-----------+--------+");
            Console.WriteLine("| {0,6} | {1,-10} | {2,-9} | {3,6} |", staff.Number,
                staff.FName, staff.LName, staff.Wage);
        }
        Console.WriteLine("+=======+============+===========+=========+");

        Console.WriteLine();
        return 0;
    }
}

No comments :