Home >Backend Development >C++ >How Can LINQ Efficiently Group a List of Objects into a List of Lists?
Group objects into a list of lists using LINQ
When dealing with complex data structures, effective management and organization of data is crucial. The powerful LINQ library in C# allows concise and efficient data manipulation. This question explores a specific scenario where a list of objects needs to be grouped based on a specific field, resulting in a new list of lists.
The provided code snippet shows a class called User that has UserID, UserName, and GroupID properties. Created a sample list of users with different group IDs. The goal is to use LINQ to group these users by their group association.
The original approach used GroupBy to achieve this, but ran into the problem of returning a list of keys. To solve this problem, the method needs to be modified slightly. The following code demonstrates the correct implementation:
<code class="language-csharp">var groupedCustomerList = userList .GroupBy(u => u.GroupID) .Select(grp => grp.ToList()) .ToList();</code>
This method effectively groups users by GroupID, producing a hierarchical list of lists. Each outer list represents a group, and each inner list contains users who belong to that group. This structure enables easy access and manipulation of grouped user data.
The above is the detailed content of How Can LINQ Efficiently Group a List of Objects into a List of Lists?. For more information, please follow other related articles on the PHP Chinese website!