LINQ and ordering of the result set

After filtering and retrieving the records most of the time (if not always) we have to sort the record in certain order. The sort order is very important for displaying records or major calculations. In LINQ for sorting data the order keyword is used.

With the help of the order keyword we can decide on the ordering of the result set that is retrieved after the query.  Below is an simple example of the order keyword in LINQ.

    string[] words = { "cherry", "apple", "blueberry" };

    var sortedWords =

        from word in words

        orderby word

        select word;

Here we are ordering the data retrieved based on the string ordering. If required the order can also be made on any of the property of the individual like the length of the string.

    var sortedWords =

        from word in words

        orderby word.Length

        select word;

You can also make the order descending or ascending by adding the keyword after the parameter.

    var sortedWords =

        from word in words

        orderby word descending

        select word;

But the best part of the order clause is that instead of just passing a field you can also pass the order clause an instance of any class that implements IComparer interface. The IComparer interface holds a method Compare that Has to be implemented. In that method we can write any logic whatsoever for the comparision. In the below example we are making a string comparison by ignoring the case.

string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "cHeRry"};

var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());

 

public class CaseInsensitiveComparer : IComparer<string>

{

    public int Compare(string x, string y)

    {

        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);

    }

}

 

But while sorting the data many a times we want to provide more than one sort so that data is sorted based on more than one condition. This can be achieved by proving the next order followed by a comma.

    var sortedWords =

        from word in words

        orderby word , word.length

        select word;

We can also use the reverse() method to reverse the full order of the result set.

    var sortedWords =

        from word in words

        select word.Reverse();                                

Vikram

2 Comments

  • You don't need the CaseInsensitiveComparer class - there's a built-in StringComparer class, which exposes static instances that match the StringComparison enumeration:

    words.OrderBy(w => w, StringComparer.OrdinalIgnoreCase)

  • @RichardD, @CW

    I used the CaseInsensitiveComparer just as an example. to show that we can write out own. May be I should have used a better example. Thanks for the comment though.

Comments have been disabled for this content.