Group list of objects into nested lists using LINQ
Efficient data organization is crucial in the field of programming. LINQ provides a powerful mechanism for grouping objects based on specific conditions. This article will solve a common problem: grouping a list of objects into a new list containing nested lists.
Consider the following class definition:
<code>public class User { public int UserID { get; set; } public string UserName { get; set; } public int GroupID { get; set; } }</code>
In order to group users based on their GroupID, we can utilize the following code:
<code>var groupedCustomerList = userList .GroupBy(u => u.GroupID) .Select(grp => grp.ToList()) .ToList();</code>
Code interpretation:
This LINQ expression cleverly groups the original list of users by GroupID, presenting them in an organized manner. Each nested list in the final result represents a group of users sharing the same GroupID.
The above is the detailed content of How Can LINQ Group a List of Objects into Nested Lists?. For more information, please follow other related articles on the PHP Chinese website!