Ordering Operators (LINQ)
Posted by Rajinder
Last Updated: July 22, 2012
  1113

ordering operator are used to order the sequence of elements in collection object. 

Example 1:

This sample uses orderby to sort a list of words alphabetically.

public void Linq28() 
{ 
    string[] words = { "cherry""apple""blueberry" }; 
  
    var sortedWords = 
        from w in words 
        orderby w 
        select w; 
  
    Console.WriteLine("The sorted list of words:"); 
    foreach (var w in sortedWords) 
    { 
        Console.WriteLine(w); 
    } 
}
Example 2:

This sample uses orderby and descending to sort a list of doubles from highest to lowest.

public void Linq32() 
{ 
    double[] doubles = { 1.72.31.94.12.9 }; 
  
    var sortedDoubles = 
        from d in doubles 
        orderby d descending 
        select d; 
  
    Console.WriteLine("The doubles from highest to lowest:"); 
    foreach (var d in sortedDoubles) 
    { 
        Console.WriteLine(d); 
    } 
}

Example 3:

This sample uses a compound orderby to sort a list of digits, first by length of their name, and then alphabetically by the name itself.

public void Linq35() 
{ 
    string[] digits = { "zero""one""two""three""four""five""six""seven""eight""nine" }; 
  
    var sortedDigits = 
        from d in digits 
        orderby d.Length, d 
        select d; 
  
    Console.WriteLine("Sorted digits:"); 
    foreach (var d in sortedDigits) 
    { 
        Console.WriteLine(d); 
    } 
}

Example 4:

This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive descending sort of the words in an array.

public void Linq38() 
{ 
    string[] words = { "aPPLE""AbAcUs""bRaNcH""BlUeBeRrY""ClOvEr""cHeRry" }; 
  
    var sortedWords = 
        words.OrderBy(a => a.Length) 
             .ThenByDescending(a => a, new CaseInsensitiveComparer()); 
  
    ObjectDumper.Write(sortedWords); 
} 
  
public class CaseInsensitiveComparer : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); 
    } 
}
   
  
 
 
   

 
 

Result Example 1

The sorted list of words:
apple
blueberry
cherry

 
 Result Example 2

The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7