Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two arrays into one Dictionary

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.

like image 292
Terry Avatar asked Nov 03 '16 09:11

Terry


2 Answers

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());
}
like image 62
Gilad Green Avatar answered Sep 20 '22 02:09

Gilad Green


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

Outcome:

  A [1, 5]
  B [2]
  D [2]
like image 29
Dmitry Bychenko Avatar answered Sep 20 '22 02:09

Dmitry Bychenko