【发布时间】:2011-04-28 00:55:01
【问题描述】:
我有以下代码:
using System.Collections.Generic;
public class Test
{
static void Main()
{
var items = new List<KeyValuePair<int, User>>
{
new KeyValuePair<int, User>(1, new User {FirstName = "Name1"}),
new KeyValuePair<int, User>(1, new User {FirstName = "Name2"}),
new KeyValuePair<int, User>(2, new User {FirstName = "Name3"}),
new KeyValuePair<int, User>(2, new User {FirstName = "Name4"})
};
}
}
public class User
{
public string FirstName { get; set; }
}
如您所见,同一个 key 有多个用户。现在我想对它们进行分组并将列表对象转换为字典,其中键将相同(如上所示的 1,2)但值将是集合。像这样:
var outputNeed = new Dictionary<int, Collection<User>>();
//Output:
//1,Collection<User>
//2,Collection<User>
即他们现在被分组了。
我怎样才能做到这一点?
【问题讨论】:
标签: c# generics dictionary key-value