小编典典

使用Linq将对象列表分组为新的对象列表分组列表

c#

我不知道这在Linq中是否可行,但是这里…

我有一个对象:

public class User
{
  public int UserID { get; set; }
  public string UserName { get; set; }
  public int GroupID { get; set; }
}

我返回的列表可能如下所示:

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 } );

我希望能够在上面的列表上运行按GroupID将所有用户分组的Linq查询。因此,输出将是包含用户的用户列表的列表(如果有意义)。就像是:

GroupedUserList
    UserList
        UserID = 1, UserName = "UserOne", GroupID = 1
        UserID = 2, UserName = "UserTwo", GroupID = 1
        UserID = 4, UserName = "UserFour", GroupID = 1
    UserList
        UserID = 3, UserName = "UserThree", GroupID = 2
    UserList
        UserID = 5, UserName = "UserFive", GroupID = 3
        UserID = 6, UserName = "UserSix", GroupID = 3

我试过使用groupby linq子句,但这似乎返回一个键列表,并且未按正确分组:

var groupedCustomerList = userList.GroupBy( u => u.GroupID ).ToList();

阅读 216

收藏
2020-05-19

共1个答案

小编典典

var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .Select(grp => grp.ToList())
    .ToList();
2020-05-19