我不知道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();
答案 0 :(得分:261)
var groupedCustomerList = userList
.GroupBy(u => u.GroupID)
.Select(grp => grp.ToList())
.ToList();
答案 1 :(得分:29)
您的群组声明将按群组ID分组。例如,如果你然后写:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
应该可以正常工作。每个组都有一个键,但也包含一个IGrouping<TKey, TElement>
,它是一个允许您迭代组成员的集合。正如李提到的那样,如果你真的想要,你可以将每个组转换成一个列表,但是如果你只是按照上面的代码迭代它们,那么这样做没有任何实际好处。
答案 2 :(得分:3)
对于类型
public class KeyValue
{
public string KeyCol { get; set; }
public string ValueCol { get; set; }
}
集合
var wordList = new Model.DTO.KeyValue[] {
new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};
我们的linq查询如下所示
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };
或数组而不是下面的列表
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };
答案 3 :(得分:-1)
仍然是一个旧的,但是李的回答没有给我这个小组。因此,我正在使用以下语句对列表进行分组并返回分组后的列表:
public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;
groupedCustomerList =
from User in userList
group User by User.GroupID into newGroup
orderby newGroup.Key
select newGroup;
每个组现在都有一个密钥,但是还包含一个IGrouping,它是一个集合,允许您遍历该组的成员。