What is the purpose of groupby in linq?
In LINQ, the GroupBy method is used to group elements in a sequence based on a specified key.
The purpose of the GroupBy method is to group elements in a sequence according to a specified key, and return a sequence containing the results of the grouping. Each group is a collection containing the key and elements associated with that key.
Using the GroupBy method makes it easy to group data for aggregation, filtering, or other operations. It is a way to achieve similar functionality to the GROUP BY clause in SQL.
Here is a sample code demonstrating how to use the GroupBy method to group a list of strings by their length.
string[] words = { "apple", "banana", "cherry", "date", "elderberry", "fig", "grape" };
var groups = words.GroupBy(w => w.Length);
foreach (var group in groups)
{
Console.WriteLine($"Words with length {group.Key}:");
foreach (var word in group)
{
Console.WriteLine(word);
}
}
The results are as follows:
Words with length 5:
apple
grape
Words with length 6:
banana
cherry
Words with length 4:
date
Words with length 10:
elderberry
Words with length 3:
fig