gpt4 book ai didi

c# - 将键值对分组到字典

转载 作者:行者123 更新时间:2023-11-30 13:24:32 24 4
gpt4 key购买 nike

我有以下代码:

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>

即他们现在分组了。

我怎样才能做到这一点?

最佳答案

我建议您使用 Lookup<TKey, TElement> 反而。此数据结构专门用作从键到值集合的映射。

//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>

关于c# - 将键值对分组到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3977979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com