我有以下代码:
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; }
}正如您在上面看到的,同一密钥有多个用户。现在我想将它们分组,并将列表对象转换为字典,其中的键将是相同的(如上所示的1,2),但值将是collection.Like this:
var outputNeed = new Dictionary<int, Collection<User>>();
//Output:
//1,Collection<User>
//2,Collection<User>也就是说,它们现在被组合在一起。
我怎样才能做到这一点呢?
发布于 2010-10-20 20:52:59
我建议您改用。此数据结构专门用作从键到值集合的映射。
//uses Enumerable.ToLookup: the Id is the key, and the User object the value
var outputNeeded = items.ToLookup(kvp => kvp.Key, kvp => kvp.Value);当然,如果您确实需要字典(也许是为了实现可变化性),您可以这样做:
var outputNeeded = new Dictionary<int, Collection<User>>();
foreach(var kvp in list)
{
Collection<User> userBucketForId;
if(!outputNeeded.TryGetValue(kvp.Key, out userBucketForId))
{
// bucket doesn't exist, create a new bucket for the Id, containing the user
outputNeeded.Add(kvp.Key, new Collection<User> { kvp.Value });
}
else
{ // bucket already exists, append user to it.
userBucketForId.Add(kvp.Value);
}
}另外,除非您打算对Collection<T>类进行子类化,否则它并不是那么有用。你确定你不只需要一个List<User>吗
发布于 2010-10-20 21:19:20
下面是一个使用LINQ的ToDictionary的例子:
var output = items.GroupBy(kvp => kvp.Key)
.ToDictionary(group => group.Key,
group => group.Select(kvp => kvp.Value).ToList());它会产生一个Dictionary<int,List<User>>。
发布于 2010-10-20 21:02:24
给定初始变量"item“和建议的输出变量"outputNeed",您需要执行以下操作:
注意:这不是真正的c#/vb代码,所以请根据需要修改这个伪代码(我现在没有VS Studio ):
foreach (KeyValuePair<int, User> pair in items)
{
//add a new collection if this is the first time you encounter the key
if (! outputNeed.Contains(pair.Key)
{
outputNeed[pair.Key] = new ArrayList<User>());
}
//add the user to the matching collection
outputNeed.Add(pair.Key, pair.User);
}祝好运
https://stackoverflow.com/questions/3977979
复制相似问题