1

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() }; 
1
  • I retagged this to add the LINQ tag, maybe you can find some more help this way. Commented Apr 6, 2013 at 12:55

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So what will the string look like once it is grouped, sorry still learning c#
The group operation has a new structured type as its result. It implements IGrouping<Char, String> which means that it basically a key-value-pair having the first character as its key and an enumerable of strings as its value.
0
// 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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.