Home >Backend Development >C++ >How Can I Group Objects by a Common Property Using LINQ?
Group objects by common properties using LINQ
This example demonstrates how to group a list of objects based on shared properties. Using LINQ, we can achieve this using the GroupBy and Select methods.
The GroupBy method creates a collection of key-value pairs, where the keys represent unique values for the specified attributes. In this example, we group by the GroupID attribute. The resulting output will be a collection of key-value pairs, where the key is the GroupID and the value is an enumeration of all User objects that share the same GroupID.
To convert these key-value pairs into a list of grouped lists, we apply the Select method. In the Select clause, we use the ToList method to convert the value part of each key-value pair (which is an enumeration of User objects) into a list.
Putting everything together, here is the LINQ query to achieve the desired grouping:
<code>var groupedCustomerList = userList .GroupBy(u => u.GroupID) .Select(grp => grp.ToList()) .ToList();</code>
The final groupedCustomerList will be a list of lists, where each inner list contains User objects grouped by their GroupID. This structure allows you to easily access and manipulate grouped data as needed.
The above is the detailed content of How Can I Group Objects by a Common Property Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!