Sunday 12 February 2012

Sorting on Collaction List using the LINQ



Introduction


Sorting a list consists of re-arranging its members in a certain order. The arrangement depends on the type of values of the list. That is, the list can be arranged in ascending order, in chronological order, in incremental order, or in logical order.
   
Ascending Order



When you create a list, you add the items in any order of your choice. When you create a select statement, the items are added to its list in the order they appear in the main list. When treating the new list or when presenting it to the user, you may want to arrange it in alphabetical, numerical, or chronological order.


To support this operation, the LINQ provides the orderby operator. To apply it, write the operator before the select operation followed by the from list. Here is an example:


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

public class Exercise
{
    public static int Main()
    {
        var numbers = new List<int>();

        numbers.Add(12);
        numbers.Add(45);
        numbers.Add(38);
        numbers.Add(5);
        numbers.Add(128);
        numbers.Add(525);
        numbers.Add(2448);
        numbers.Add(39);
        numbers.Add(632);
        numbers.Add(207);

        var number = from n
                     in numbers
                     orderby n
                     select n;

        foreach (var member in number)
            Console.WriteLine(member.ToString());
        return 0;
    }
}


This would produce:

Order By


If you apply the orderby operator simply followed by a variable, the list is ordered alphabetically or numerically depending on the types of values in the list. This is referred to as ascending. To re-enforce this, you can follow the variable with the ascending keyword. 

Here is an example:

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

public class Exercise
{
    public static int Main()
    {
        var numbers = new List<int>();

        numbers.Add(12);
        numbers.Add(45);
        numbers.Add(38);
        numbers.Add(5);
        numbers.Add(128);
        numbers.Add(525);
        numbers.Add(2448);
        numbers.Add(39);
        numbers.Add(632);
        numbers.Add(207);

        var number = from n
                     in numbers
                     orderby n ascending
                     select n;

        foreach (var member in number)
            Console.WriteLine(member.ToString());

        return 0;
    }
}


Descending Order




You can arrange a list in reverse ascending order, in decremental order, or in reverse chronological order. To support this, the LINQ uses the orderby keyword in combination with the descending keyword. 

Here is an example:

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

public class Exercise
{
    public static int Main()
    {
        var numbers = new List<int>();

        numbers.Add(12);
        numbers.Add(45);
        numbers.Add(38);
        numbers.Add(5);
        numbers.Add(128);
        numbers.Add(525);
        numbers.Add(2448);
        numbers.Add(39);
        numbers.Add(632);
        numbers.Add(207);

        var number = from n
                     in numbers
                     orderby n descending
                     select n;

        foreach (var member in number)
            Console.WriteLine(member.ToString());

        Console.WriteLine();
        return 0;
    }
}


This would produce:

Order By Descending


Sorting With Class



Sorting the members of a primitive-based list is quite easy. This is because the classes (or structures) of each data type implement the IComparable interface. This also makes it easy to sort the values of a select statment. This means that, to arrange the list of values, in the orderby statement, type the name of the from variable and use the period operator to specify the base of what member you want to arrange the list. 

Here is an example:

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

public class Exercise
{
    public static int Main()
    {
        var 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 empls = from staffMembers
                    in employees
                    orderby staffMembers.EmployeeNumber
                    select staffMembers;

        Console.WriteLine("+========+============+===========+========+");
        Console.WriteLine("| Empl # | First Name | Last Name | Salary |");
        foreach (var staff in empls)
        {
            Console.WriteLine("+--------+------------+-----------+--------+");
            Console.WriteLine("| {0,6} | {1,-10} | {2,-9} | {3,6} |", staff.EmployeeNumber,
                staff.FirstName, staff.LastName, staff.HourlySalary);
        }
        Console.WriteLine("+=======+============+===========+=========+");

        Console.WriteLine();
        return 0;
    }
}

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

    public Employee(int number = 0,
                       string fName = "John",
                       string lName = "Doe",
                       double salary = 0D)
    {
        EmployeeNumber = number;
        FirstName = fName;
        LastName = lName;
        HourlySalary = salary;
    }
}


This would produce:

+========+============+===========+========+
| Empl # | First Name | Last Name | Salary |
+=======+============+===========+=========+
| 208411 | Raymond    | Kouma     |  20.15 |
+--------+------------+-----------+--------+
| 279374 | Hél�ne     | Mukoko    |  15.55 |
+--------+------------+-----------+--------+
| 707912 | Bertrand   | Yamaguchi |  24.68 |
+--------+------------+-----------+--------+
| 971394 | Gertrude   | Monay     |  20.55 |
+--------+------------+-----------+--------+
| 971974 | Patricia   | Katts     |  24.68 |
+--------+------------+-----------+--------+

Press any key to continue . . .

In the same way, you can specify by what member of the class the list should be sorted.

No comments :