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