可能重复:
在C#中合并字典
使用c#4有2个类型的字典
<string,List<int>>
dictionary1 = [ { "key1" , [ 1, 2, 3]} ,
{ "key2" , [ 1, 2, 4 , 6]}
]
Run Code Online (Sandbox Code Playgroud)
我想与dictionary2结合
dictionary2 = [ { "key0" , [ 1, 2, 3]} ,
{ "key2" , [ 1, 2, 3, 5 , 6]}
]
Run Code Online (Sandbox Code Playgroud)
所以得到=>
dictionary1 + dictionary2 = [ { "key1" , [ 1, 2, 3]} ,
{ "key2" , [ 1, 2, 3, 4, 5, 6]},
{ "key0" , [ 1, 2, 3]}
]
Run Code Online (Sandbox Code Playgroud)
我该怎么做 ?
一个简单的循环Enumerable.Union?:
foreach (var kv in dictionary2)
{
List<int> values;
if (dictionary1.TryGetValue(kv.Key, out values))
{
dictionary1[kv.Key] = values.Union(kv.Value).ToList();
}
else
{
dictionary1.Add(kv.Key, kv.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2577 次 |
| 最近记录: |