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.
Cool..
ReplyDeletenice question ..
ReplyDeleteits nice
ReplyDeleteAgain, informative, short and sweet. Keep going.
ReplyDeleteNice Question....
ReplyDeletecool Q & A
ReplyDeleteExcellent Work!!!!!!!!
ReplyDeleteSimply Great...!
ReplyDeleteDECENT
ReplyDeleteGood Article...
ReplyDeleteOnline LINQ
Training
LINQ Training
Online LINQ Training from India
LINQ Training in Chennai
Dot Net Training in Chennai
.Net Online Training
Good Article....
ReplyDeleteBut can you write same query in method syntax
Thanks for the great post! Your QAs have been added to the www.fullstack.cafe portal and back-linked!
ReplyDeleteThanks for the great post! More LINQ interview questions www.fullstack.cafe!
ReplyDeleteAivivu - đại lý chuyên vé máy bay trong nước và quốc tế
ReplyDeletevé máy bay đi Mỹ giá rẻ
vé máy bay từ mỹ về việt nam hãng ana
bay nhật bản việt nam
giá vé máy bay từ đức về việt nam
vé máy bay từ canada về việt nam
ve may bay vietnam airline tu han quoc ve viet nam
danh sách khách sạn cách ly tại hà nội
vé máy bay chuyên gia nước ngoài
Thankfulness to my dad who informed me relating to this blog, this website is really amazing.
ReplyDeleteexperience design companies