In C#, you can use LINQ to group data and apply various operations on it. Here is a general example of how you can use GroupBy in LINQ.
Here's an overview of GroupBy operator.
Using GroupBy in LINQ is useful for several reasons when working with collections of data.
LINQ Query with GroupBy
To group the people list by LastName, you can use the following LINQ query:
var groupedByLastName = from person in people
group person by person.LastName into grouped
select new
{
LastName = grouped.Key,
People = grouped.ToList()
};
LINQ GroupBy with Lambda
To group the people list by LastName, you can use the following LINQ query:
var groupedByLastNameLambda
= people.GroupBy(person => person.LastName)
.Select(group => new
{
LastName = group.Key,
People = group.ToList()
});
To group the people list by LastName, you can use the following LINQ query:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Program
{
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "Rohatash", LastName = "Kumar" },
new Person { FirstName = "Mohit", LastName = "Singh" },
new Person { FirstName = "Saurav", LastName = "Kumar" }
};
// Group by LastName using LINQ query
Console.WriteLine("LINQ Query Output:");
Console.WriteLine("");
var groupedByLastName = from person in people
group person by person.LastName into grouped
select new
{
LastName = grouped.Key,
People = grouped
};
foreach (var group in groupedByLastName)
{
Console.WriteLine("Last Name:" + group.LastName);
foreach (var person in group.People)
{
Console.WriteLine(person.FirstName);
}
}
// Group by LastName using Lambda
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Lambda Query Output:");
Console.WriteLine("");
var groupedByLastNameLambda = people.GroupBy(person => person.LastName)
.Select(group => new
{
LastName = group.Key,
People = group.ToList()
});
foreach (var group in groupedByLastNameLambda)
{
Console.WriteLine("Last Name:" + group.LastName);
foreach (var person in group.People)
{
Console.WriteLine(person.FirstName);
}
}
}
}
Output