You can use the group
clause in LINQ to group data by multiple columns. To do so, you can create an anonymous type that combines the values of the columns you want to group by, and then group by that anonymous type.
Here's an example of how to use group by
on multiple columns in LINQ:
csharp// create a collection of objects
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 25, Gender = "Female" },
new Person { Name = "Bob", Age = 30, Gender = "Male" },
new Person { Name = "Charlie", Age = 25, Gender = "Male" },
new Person { Name = "David", Age = 30, Gender = "Male" },
new Person { Name = "Eva", Age = 25, Gender = "Female" }
};
// group people by age and gender
var groupedPeople = from p in people
group p by new { p.Age, p.Gender };
// iterate through each group and its elements
foreach (var group in groupedPeople)
{
Console.WriteLine("Age: " + group.Key.Age + ", Gender: " + group.Key.Gender);
foreach (var person in group)
{
Console.WriteLine(" " + person.Name);
}
}
In this example, we first create a collection of Person
objects with three properties: Name
, Age
, and Gender
. We then use the group
keyword in a LINQ query to group the people by their Age
and Gender
properties. To do this, we create an anonymous type that combines the Age
and Gender
properties, and group by that anonymous type.
We then iterate through each group and its elements using a foreach
loop, printing out the Age
and Gender
of each group, and the names of the people in each group.
The output of this code will be:
yamlAge: 25, Gender: Female
Alice
Eva
Age: 30, Gender: Male
Bob
David
Age: 25, Gender: Male
Charlie
As you can see, the people have been grouped by their Age
and Gender
, and the output shows each combination of Age
and Gender
, along with the names of the people in each group.
Comments
Post a Comment