Two arrays in one dictinary

I would like to create

Dictionary<string, int[]> dict 

from two arrays:

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

result:

 ["A"] = {1,5} ["B"] = {2} ["D"] = {2} 

Is there a way I can do this with LINQ? I read about Zip, but I don’t think I can use it, since I need to add values ​​to the existing key.value array.

+6
source share
3 answers

Use .Zip to combine the two collections, and then GroupBy to group the keys.

 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()); 

Then add these elements to the dictionary that you already have: I changed int[] to List<int> , so it’s easier to handle 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()); } } 
+8
source

Linq Solution:

  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()); 

Test:

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

Result:

  A [1, 5] B [2] D [2] 
+4
source

Try the following:

  string[] keys = { "A", "B", "A", "D" }; int[] values = { 1, 2, 5, 2 }; Dictionary<string, int[]> dict = keys.Select((x, i) => new { key = x, value = values[i] }).GroupBy(x => x.key, y => y.value).ToDictionary(x => x.Key, y => y.ToArray()); 
0
source

Source: https://habr.com/ru/post/1011977/


All Articles