LINQ and ordering of the result set

Posted by vik20000in on ASP.net Weblogs See other posts from ASP.net Weblogs or by vik20000in
Published on Fri, 09 Apr 2010 03:34:00 GMT Indexed on 2010/04/09 3:43 UTC
Read the original article Hit count: 535

Filed under:
|
|
|

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

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET