LINQ orderby Clause

LINQ makes it straightforward for you to type or modify the order of the results of the question. We can use the orderby clause and specify that worth or property are going to be used as a key for sorting results. maybe, suppose we’ve associate array of numbers that we would like to question and so prepare the results from highest to lowest, we will use the subsequent question expression:

int[] numbers = { 5, 1, 6, 2, 8, 10, 4, 3, 9, 7 }; 

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

The question uses the orderby clause to order the results and that we used the quantity or the particular object because the key for ordering those results. once you use the particular object, then their default behavior once being compared is employed. let’s say, the on top of statement can compare the values of every queried whole number and tests that is larger or smaller than the opposite one. The default behavior of the orderby clause is to kind the results from lowest to highest. we are able to expressly command the question to kind it in ascending order by mistreatment the ascending keyword.

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

To reverse its impact, that is, to type values from highest to lowest, we are able to append the descending keyword in the orderby clause.

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

In cases where complex types are involved, you can use their properties as the key for ordering the results of a query. For example, suppose we have a collection of  Person objects which has FirstNameLastName, and Age properties. We can sort the results from the youngest to the oldest person using the following query.

var sortedByAge = from person in people
                  orderby person.Age
                  select person;

Again, we can use the descending keyword if you want to reverse the order of the query. We can also sort the results alphabetically based on each person’s last name.

var sortedByFirstName = from person in people
                        orderby person.LastName
                        select person;

What if 2 persons have an equivalent last name? however can those things with an equivalent values be sorted? we are able to specify multiple values within the orderby clause if you’d wish to properly handle cases like these.

var sortedByFnThenLn = from person in people
                       orderby person.LastName, person.FirstName
                       select person;

We isolate each arranging key in the orderby clause by commas. The question on top of kinds the result supported each person’s LastName, and if multiple persons have the same LastName, their FirstName will then be sorted. you’ll be able to specify even additional keys in orderby if, parenthetically, 2 persons still has the same FirstName. Note that using ascending or descending only affects one price in the orderbyclause. parenthetically, employing a question like this with a descending keyword:

var orderByResults = from person in people
                     orderby person.LastName, person.FirstName descending
                     select person;

only affects the property preceding it, in this case, FirstNameLastName will be ordered in ascending order by default. You can explicitly specify the order to avoid confusion.

var orderByResults = from person in people
                     orderby person.LastName ascending, person.FirstName descending
                     select person;

A class can implement the IComparable<T> interface which determines the default way an object can be sorted. The definition of the Person class is presented below showing an implementation of the IComparable<T> interface.

class Person : IComparable<Person>
{
       //set to variable name according to me
    public string Firstone( { get; set; }
    public string Lastone { get; set; }
    public int Ageone { get; set; }
 
    public Person(string fn, string ln, int age)
    {
        First = fn;
        Last = ln;
        Age = age;
    }
 
    public int CompareTo(Person other)  
    {                                   
        if (this.Age > other.Age)       
            return 1;                   
        else if (this.Age < other.Age)  
            return -1;                  
        else //if equal                 
            return 0;                   
    }                                   
}

Example 1

Line 1 specifies that the method implements IComparable<T> interface. We need to replace T with the type of the object to be compared, in this case, Person. Implementing that interface requires you to  implement a method named CompareTo() which accepts the other object to be compared to this instance and returns an integer value which is the result of the comparison. Lines 14 to 22 defines that method and inside it, we test whether the  Age of this instance is greater than, less than, or equal to the other  Person being compared. A value greater than 0 is returned if the value from this instance is greater than the value of the other. A value less than 0 is returned if the value of this instance is less than the other, and 0 if both values are equal. We can simply use 1 for greater than, -1 for less than, or 0 for equal. Now that a class implements the IComparable<T> interface, we can simplify the LINQ query. Since we used the Age property inside the CopareTo method, not specifying a property as a key for ordering the results in a LINQ query will sort the results based on each person’s age.

List<Person> people = new List<Person>() { new Person("Peter", "Redfield", 32), 
                                           new Person("Marvin", "Monrow", 17),
                                           new Person("Aaron", "Striver", 25) };

var defaultSort = from person in people   
                  orderby person        
                  select person;         

foreach (var person in defaultSort)
{
    Console.WriteLine(String.Format("{0} {1} {2}", person.Age, person.FirstName, person.LastName));
}
17 Marvin Monrow
25 Aaron Striver
32 Peter Redfield

The OrderBy() and OrderByDescending() Methods


The OrderBy() and OrderByDescending() methods in System.Linq are the corresponding LINQ strategies of the orderby clause. The OrderBy() technique types the leads to ascending order supported a fixed key, and the OrderByDescending() technique is that the opposite that types the leads to down order. we will pass a lambda expression specifying the key to be used for sorting.

int[] numbers = { 5, 1, 6, 2, 8, 10, 4, 3, 9, 7 }; 

List<Person> people = GetPersonList();

var orderByQueryone = numbers.OrderBy( number => number );

var orderByQuerytwo = numbers.OrderByDescending( number => number );

var orderByQuerythree = people.OrderBy( person => person.First );

var orderByQuery4 = people.OrderByDescending( person => person.Age );

The ThenBy() and ThenByDescending() Methods


On the off chance that you have numerous keys that you need to utilize, at that point you can utilize the ThenBy() and ThenByDescending() methods. For instance, the LINQ inquiry:

var orderByQuery5 = from p in people
                    orderby p.Last, p.First
                    select p;

is equivalent to the following.

var orderByQuery5 = people.OrderBy(p => p.Last).ThenBy(p => p.First);

You can utilize the ThenByDescending() method on the off chance that you need the accompanying keys to sort brings about diving request.

var orderByQuery6 = people.OrderBy(p=>p.Last).ThenByDescending(p=>First);

var orderByQuery7 = people.OrderByDescending(p=>p.Last)
                          .ThenByDescending(p=>p.First);

Note that ThenBy() and ThenByDescending() are techniques of IOrderedEnumerable<T> interface and the OrderBy() methods and the orderby statement restores an accumulation executing this interface.In this way, you should use OrderBy() or OrderByDescending() before calling ThenBy() or ThenByDescending().

Using an IComparer<T> Interface Object


An over-burden rendition of the four talked about requesting strategies acknowledges a second comparer protest contention. We can make a comparer class which actualizes the IComparer<TKey> interface.

class FirstNameComparer : IComparer<Person>
{
    public int Compare(Person x, Person y) 
    { 
        return x.First.CompareTo(y.First); 
    }
}

The interface will require you to create an implementation for it’s Compare() method which is similar to the CompareTo() method  of the IComparable<T> described earlier, except that it accepts two arguments which are the objects to be compared. We just utilize the CompareTo() method of the String class which likewise returns and whole number. We thought about the FirstNames of the people being looked at.

We can then pass an instance of this comparer as a second argument to the OrderByOrderByDescendingThenBy, or ThenByDescending.

var orderByQuery8 = people.OrderBy(person => person, new FirstNameComparer());

The second argument will then affect which key to use when ordering the results of a query. The above strategy call essentially utilizes the entire individual as the key, and with the assistance of the FirstNameComparer object, the technique naturally arranges the outcome by each person’s FirstName property.

An option for utilizing techniques for requesting in diving request and utilizing the sliding catchphrase is the Reverse() method.

var orderByQuery9 = (from person in people
                     orderby person.First
                     select person).Reverse();
var orderByQeury10 = people.OrderBy(person => person.First).Reverse();

On the first example, the whole query is enclosed in parentheses to treat it as one  and then we used the Reverse() method to the  result of the query. The second example is the same as the first but uses the  method syntax.