0

Was hoping I could ask for advice.

I have two dictionaries

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> dictFinal = new Dictionary<string, List<string>>();

In both cases the key values are the same but the both represent different lists of string values.

enter image description here

What I want is to have one dictionary with the same key values and with the lists of string values to be merged in one dictionary

enter image description here

I did start with a serious of loops but soon realised that this is perhaps not the best solution

foreach (var fin in dictFinal)
            {
                foreach (var valFin in fin.Value)
                {
                    foreach (var kvp in dict)
                    {
                        foreach (var v in kvp.Value)
                        {

                        }
                    }

                }

            }

Is there a better way for bringing these two dictionaries 'together'?

Arianule
  • 8,097
  • 41
  • 108
  • 163

3 Answers3

3
Dictionary<string, List<string>> d1 = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> d2 = new Dictionary<string, List<string>>();
d2.ToList().ForEach(x =>
                         {
                           if (d1.ContainsKey(x.Key))
                             d1[x.Key].AddRange(x.Value);
                           else
                             d1.Add(x.Key, x.Value);
                         });

That will merge both dictionaries into d1.

Without ToList()

foreach(var x in d1)
{
  if (d1.ContainsKey(x.Key))
    d1[x.Key].AddRange(x.Value);
  else
    d1.Add(x.Key, x.Value);
}
LukeHennerley
  • 6,046
  • 27
  • 48
  • 1
    Please, don't use the `ToList()` only to use the `ForEach`... It's terrible... The `ForEach` method in linq is a semi-abomination (see http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)... But converting a collection to a `List` just to use the `ForEach` method... – xanatos Feb 21 '13 at 09:33
  • @xanatos the link is broken but I understand why, I think :) – LukeHennerley Feb 21 '13 at 09:58
  • Aaaaah... The link was mangled with the endling ). ... Ok... Let's retry! http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx – xanatos Feb 21 '13 at 10:03
1

I would use loops. Assuming merging means that the lists should contain unique strings:

foreach (var kvp in dict)
{
    List<string> listInDict2;
    if (dictFinal.TryGetValue(kvp.Key, out listInDict2))
        dictFinal[kvp.Key] = kvp.Value.Union(listInDict2).ToList();
    else
        dictFinal.Add(kvp.Key, kvp.Value);
}
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
1

You can try with the

UNION or JOIN methods to merge the results

dictFinal.union or dictFinal.join

Jerald
  • 335
  • 1
  • 9