Rifki
Rifki

Reputation: 901

Using group by in C#

Could anyone explain what this sample of code is doing? I can't quite grasp how the words string is being grouped. Is it taking the first letter of each word and grouping them somehow?

// Create a data source. 
        string[] words = { "apples", "blueberries", "oranges", "bananas", "apricots" };

        // Create the query. 
        var wordGroups1 =
            from w in words
            group w by w[0] into fruitGroup
            where fruitGroup.Count() >= 2
            select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };

Upvotes: 1

Views: 201

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

// Create a data source. 
string[] words = { "apples", "blueberries", "oranges", "bananas", "apricots" };

// Create the query. 
var wordGroups1 =
    from w in words                  //w is every single string in words
    group w by w[0] into fruitGroup  //group based on first character of w
    where fruitGroup.Count() >= 2    //select those groups which have 2 or more members
                                     //having the result so far, it makes what is needed with select
    select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };

Another example. In the array show the frequency of string's length:

var wordGroups1 =
    from w in words                  
    group w by w.Length into myGroup  
    select new { StringLength = myGroup.Key, Freq = myGroup.Count() };

//result: 1 6-length string
//        1 11-length string
//        2 7-length string
//        1 8-length string

Upvotes: 0

Simon Opelt
Simon Opelt

Reputation: 6201

The LINQ query groups all the words by their first character. It then removes all groups which contain only one element (=keeps all groups with two or more elements). At the end the groups are filled into new anonymous objects containing the first letter and number of words found starting with that letter.

The LINQ Documentation and samples should get you started reading and writing code like that.

Upvotes: 2

Related Questions