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