Explain with an example how to perform group by in LINQ/LAMBDA?

 Posted by Niladri.Biswas on 7/12/2012 | Category: LINQ Interview questions | Views: 6802 | Points: 40
Answer:

Consider the below input

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

The problem is to write a query using LINQ and LAMBDA that will count the nunber of fruits.

Solution
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };


//Using LINQ
(from a in input
group a by a into g
select new
{
Key = g.Key
,Count = g.Count()

})
.ToList()
.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));

//Using Lambda
input
.GroupBy(g => g)
.Select(i => new { Key = i.Key, Count = i.Count() })
.ToList()
.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));


Output
Number of Apple is 3

Number of Banana is 1
Number of Mango is 2
Number of Orange is 1
Number of Strawberry is 1


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response