Grouping data in LINQ with the help of group keyword

Posted by vik20000in on ASP.net Weblogs See other posts from ASP.net Weblogs or by vik20000in
Published on Tue, 13 Apr 2010 10:53:00 GMT Indexed on 2010/04/13 11:03 UTC
Read the original article Hit count: 673

Filed under:
|
|
|

While working with any kind of advanced query grouping is a very important factor. Grouping helps in executing special function like sum, max average etc to be performed on certain groups of data inside the date result set. Grouping is done with the help of the Group method. Below is an example of the basic group functionality.

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

   

    var numberGroups =

        from num in numbers

        group num by num % 5 into numGroup

        select new { Remainder = numGroup.Key, Numbers = numGroup };

 

In the above example we have grouped the values based on the reminder left over when divided by 5. First we are grouping the values based on the reminder when divided by 5 into the numgroup variable.  numGroup.Key gives the value of the key on which the grouping has been applied. And the numGroup itself contains all the records that are contained in that group.

Below is another example to explain the same.

string[] words = { "blueberry", "abacus", "banana", "apple", "cheese" };

   

    var wordGroups =

        from num in words

        group num by num[0] into grp

        select new { FirstLetter = grp.Key, Words = grp };


In the above example we are grouping the value with the first character of the string (num[0]).

Just like the order operator the group by clause also allows us to write our own logic for the Equal comparison (That means we can group Item by ignoring case also by writing out own implementation). For this we need to pass an object that implements the IEqualityComparer<string> interface. Below is an example.

public class AnagramEqualityComparer : IEqualityComparer<string>

{

    public bool Equals(string x, string y) {

        return getCanonicalString(x) == getCanonicalString(y);

    }

 

    public int GetHashCode(string obj) {

        return getCanonicalString(obj).GetHashCode();

    }

   

    private string getCanonicalString(string word) {

        char[] wordChars = word.ToCharArray();

        Array.Sort<char>(wordChars);

        return new string(wordChars);

    }

}

 

string[] anagrams = {"from   ", " salt", " earn", "  last   ", " near "};

var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());

Vikram

 

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET