Terry Terry - 29 days ago 6
C# Question

Two arrays into one Dictinary

I would like to create a

Dictionary<string, int[]> dict


out of two arrays:

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


the result:

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


Is there a way i can do this with LINQ?
I have read about Zip but I don't think I can use since I need to add values to an existing key.value array.

Answer

Use .Zip to bind the two collections together 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 to add these items into the dictionary that you already have: I changed the int[] to List<int> so it is 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());
    }
}
Comments