参考这个问题 - Using Linq to group a list of objects into a new grouped list of list of objects。
这是输入:
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 } );
我希望结果采用以下格式:
GroupedUserList
GroupID UserIdList UsersList
1 , [1,2,4], ["User1", "UserTwo", "UserFour"]
2 , [3], ["UserThree"]
3 , [5,6], ["UserFive", "UserSix"]
linq查询是什么?
答案 0 :(得分:2)
您可以在GroupID
上执行该组,然后以这种方式投影生成的组:
var result = userList.GroupBy(user=>user.GroupID)
.Select(group=> new
{
GroupID = group.Key,
UserIDs = String.Join(",", group.Select(x=>x.UserID)),
UserNames = String.Join(",", group.Select(x=>x.UserName))
});
result
将包含每个GroupID
,其中UserID
和UserName
为逗号分隔字符串。
编辑:
如果您需要List
而不是逗号分隔值,则只需移除String.Join
来电并使用ToList()
实现结果:
var result = userList.GroupBy(user=>user.GroupID)
.Select(group=> new
{
GroupID = group.Key,
UserIDs = group.Select(x=>x.UserID).ToList(),
UserNames = group.Select(x=>x.UserName).ToList()
});
答案 1 :(得分:1)
您确定不想将{UserId,UserName}的每个元组放在一起吗?
GroupId {UserId, UserName}
1 {1, "User1}, {2, "UserTwo"}, {4, "UserFour"},
2 {3, "UserThree"}
...
如果您确定不需要,那么您需要在GroupBy之后进行选择:
var result = userList.GroupBy(user => user.UserId)
.Select(group => new
{
UserIdList = group.Select(user => user.UserId).ToList(),
UsersList = group.Select(user => user.UserName).ToList(),
});