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()); } }
source share