两个数组合成一个Dictinary

Ter*_*rry 6 c# linq arrays dictionary

我想创建一个

 Dictionary<string, int[]> dict
Run Code Online (Sandbox Code Playgroud)

两个数组:

string[] keys = { "A", "B", "A", "D" };
int[] values = { 1, 2, 5, 2 };
Run Code Online (Sandbox Code Playgroud)

结果:

["A"] = {1,5} 
["B"] = {2}
["D"] = {2}
Run Code Online (Sandbox Code Playgroud)

有没有办法用LINQ做到这一点?我已经阅读了Zip,但我认为我不能使用,因为我需要为现有的key.value数组添加值.

Gil*_*een 8

使用.Zip两个集合在一起,然后绑定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());
Run Code Online (Sandbox Code Playgroud)

然后将这些项添加到您已有的字典中: 我将其更改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());
    }
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 5

林克解决方案:

  string[] keys = { "A", "B", "A", "D" };
  int[] values = { 1, 2, 5, 2 };

  Dictionary<string, int[]> dict = keys
    .Zip(values, (k, v) => new {
       key = k,
       value = v })
    .GroupBy(pair => pair.key, pair => pair.value)
    .ToDictionary(chunk => chunk.Key, 
                  chunk => chunk.ToArray());
Run Code Online (Sandbox Code Playgroud)

测试:

  string report = String.Join(Environment.NewLine, dict
    .Select(pair => $"{pair.Key} [{string.Join(", ", pair.Value)}]"));

  Console.Write(report);
Run Code Online (Sandbox Code Playgroud)

结果:

  A [1, 5]
  B [2]
  D [2]
Run Code Online (Sandbox Code Playgroud)