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
be
to
Words of length: 3, Count: 3
can
and
too
Words of length: 4, Count: 3
LINQ
used
them
Words of length: 5, Count: 3
group
words
count

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)
Console.WriteLine(word);
}
}

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

15 comments:

  1. nice question ..

    ReplyDelete
  2. Again, informative, short and sweet. Keep going.

    ReplyDelete
  3. Nice Question....

    ReplyDelete
  4. Good Article....
    But can you write same query in method syntax

    ReplyDelete
  5. Thanks for the great post! Your QAs have been added to the www.fullstack.cafe portal and back-linked!

    ReplyDelete
  6. Thanks for the great post! More LINQ interview questions www.fullstack.cafe!

    ReplyDelete
  7. Thankfulness to my dad who informed me relating to this blog, this website is really amazing.
    experience design companies

    ReplyDelete