Group a list of objects using LINQ
In object-oriented programming, it is often necessary to group objects according to sharing conditions. This can be done efficiently using LINQ (Language Integrated Query). Below we'll explore how to group a list of objects into a new grouped list that contains multiple object lists.
Question:
Consider a class representing a user:
<code class="language-csharp">public class User { public int UserID { get; set; } public string UserName { get; set; } public int GroupID { get; set; } }</code>
Suppose we have a list of users:
<code class="language-csharp">List<User> userList = new List<User>(); userList.Add(new User { UserID = 1, UserName = "UserOne", GroupID = 1 }); userList.Add(new User { UserID = 2, UserName = "UserTwo", GroupID = 1 }); userList.Add(new User { UserID = 3, UserName = "UserThree", GroupID = 2 }); userList.Add(new User { UserID = 4, UserName = "UserFour", GroupID = 1 }); userList.Add(new User { UserID = 5, UserName = "UserFive", GroupID = 3 }); userList.Add(new User { UserID = 6, UserName = "UserSix", GroupID = 3 });</code>
Our goal is to group users by their GroupID, resulting in a list of users grouped by group.
Solution:
LINQ provides a powerful grouping mechanism using the GroupBy method. The following code snippet demonstrates how to achieve the desired grouping:
<code class="language-csharp">var groupedUserList = userList .GroupBy(u => u.GroupID) .Select(grp => grp.ToList()) .ToList();</code>
Code breakdown:
IGrouping<int, User>
), we need to select users from each group. We use ToList method in Select to convert each group into a list of users. groupedUserList
now contains the required grouping: a list of user lists, where each inner list represents a user that belongs to the same group.
The above is the detailed content of How Can I Group a List of Objects by a Shared Property Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!