小编典典

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

all

我不知道这在 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 } );

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

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

阅读 60

收藏
2022-07-31

共1个答案

小编典典

var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .Select(grp => grp.ToList())
    .ToList();
2022-07-31