In LINQ, you can use the Group By clause to group a collection of elements based on a specific key or property. The Group By clause returns a sequence of groupings, where each grouping consists of a key and a sequence of elements that share the same key.
Here's an example of using Group By in LINQ:
csharp// create a collection of objects
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 25 },
new Person { Name = "David", Age = 30 },
new Person { Name = "Eva", Age = 25 }
};
// group people by age
var groupedPeople = from p in people
group p by p.Age;
// iterate through each group and its elements
foreach (var group in groupedPeople)
{
Console.WriteLine("Age: " + group.Key);
foreach (var person in group)
{
Console.WriteLine(" " + person.Name);
}
}
In this example, we first create a collection of Person
objects. We then use the group
keyword in a LINQ query to group the people by their age property. This creates a sequence of groupings, where each grouping has a key (the age) and a sequence of elements (the people with that age).
We then iterate through each group and its elements using a foreach
loop, printing out the age and the names of the people in each group.
The output of this code will be:
makefileAge: 25
Alice
Charlie
Eva
Age: 30
Bob
David
As you can see, the people have been grouped by their age, and the output shows each age and the names of the people with that age.
Comments
Post a Comment