Group words by length in CSharp
Description
The following code shows how to group words by length.
Example
//from w ww. jav a2 s .c o m
using System;
using System.Linq;
class HelloWorld {
static void Main() {
string[] words = { "A", "ss", "wa", "ccc", "a" };
var groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups };
foreach (var group in groups) {
Console.WriteLine("Words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
}
}
The code above generates the following result.