我想创建一个
Dictionary<string, int[]> dict
两个数组中的:
string[] keys = { "A", "B", "A", "D" };
int[] values = { 1, 2, 5, 2 };
结果:
["A"] = {1,5}
["B"] = {2}
["D"] = {2}
有什么方法可以用 LINQ 做到这一点吗? 我读过 Zip,但我认为我无法使用,因为我需要将值添加到现有的 key.value 数组。
最佳答案
使用 .Zip
将两个集合绑定(bind)在一起,然后 GroupBy
对键进行分组。
string[] keys = { "A", "B", "A", "D" };
int[] values = { 1, 2, 5, 2 };
var result = keys.Zip(values, (k, v) => new { k, v })
.GroupBy(item => item.k, selection => selection.v)
.ToDictionary(key => key.Key, value => value.ToArray());
然后将这些项目添加到您已有的字典中:
我更改了 int[]
至 List<int>
所以更容易处理Add/AddRange
Dictionary<string, List<int>> existingDictionary = new Dictionary<string, List<int>>();
foreach (var item in result)
{
if (existingDictionary.ContainsKey(item.Key))
existingDictionary[item.Key].AddRange(item.Value);
else
existingDictionary.Add(item.Key, item.Value.ToList());
}
关于c# - 两个数组合并成一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397541/