Please navigate to the bottom of the page for Table of Contents

Tuesday, June 14, 2011

LINQ - Group, Sort and Count Words in a sentence by length

LINQ has been around for some time now to make up to the programming interview list. With the proliferation of Entity Framework, this has become more popular. Let’s start our LINQ interview question series with a serious question:

Question: Given a sentence, group the words of same length, sort the groups in increasing order and display the groups, the word count and the words.

For example, the following sentence: “LINQ can be used to group words and count them too” should result in an output like:

Words of length: 2, Count: 2
Words of length: 3, Count: 3
Words of length: 4, Count: 3
Words of length: 5, Count: 3

Let’s look at the code. The function to do solve this is quite simple. I have commented the code to highlight the LINQ operations that parse the sentence and converts it into relevant solution.

static void Main(string[] args)
SentenceParsing("LINQ can be used to group words and count them too");

public static void SentenceParsing(string sentence)
// Split the string into individual words to create a collection.
string[] words = sentence.Split(' ');

// LINQ query
var query =
from w in words // for all the words
group w by w.Length into grp // group them by length
orderby grp.Key // order by length
select new
{ // create a new object with the required props
Length = grp.Key,
Words = grp,
WordCount = grp.Count()

// execute the query
foreach (var obj in query)
Console.WriteLine("Words of length: {0}, Count: {1}",
obj.Length, obj.WordCount);
foreach (string word in obj.Words)

In the next post we will explore a bunch of simple LINQ interview questions.