gpt4 book ai didi

c# - 合并 IDictionary - 有比这更有效的方法吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:36 26 4
gpt4 key购买 nike

我有一个助手可以合并两个或更多 IDictionary<TKey, TValue>物合一IDictionary<TKey, string>通过连接 TValueToString()像这样的方法:

public class DictionaryHelper<TKey, TValue>
{
public static IDictionary<TKey, string> MergeDictionaries<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries) where TValue : class
{
var returnValue = new Dictionary<TKey, string>();
foreach (var dictionary in dictionaries)
{
foreach (var kvp in dictionary)
{
if (returnValue.ContainsKey(kvp.Key))
{
returnValue[kvp.Key] += kvp.Value.ToString();
}
else
{
returnValue[kvp.Key] = kvp.Value.ToString();
}
}
}
return returnValue;
}

}

虽然这很简单易读,但似乎应该有更有效的方法来做到这一点。有吗?

最佳答案

我不知道这是否更有效,但至少它更短:

var result = dictionaries.SelectMany(d => d)
.ToLookup(kvp => kvp.Key, kvp => kvp.Value)
.ToDictionary(g => g.Key, g => string.Concat(g));

关于c# - 合并 IDictionary - 有比这更有效的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10398751/

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