views:

78

answers:

1

I'm developing an app in C# targeting .NET 3.5. In it, I have 2 similar dictionaries that contain validation criteria for a specific set of elements in my app. Both dictionaries have identical signatures. The first dictionary has the default settings and the 2nd dictionary contains some user defined settings.

var default_settings = new Dictionary<string, MyElementSettings>();
var custom_settings = new Dictionary<string, MyElementSettings>();

I would like to combine the 2 dictionaries into one that contains the elements of both dictionaries.

The problem that I am running into is it is possible for both dictionaries to have the some of the same key values. The basic rule I want is to have a combination of both dictionary and if there are any keys in the custom_settings that already exist in the default_settings, the custom_settings value will overwrite the default_settings value. The best solution i have is just a foreach loop, check if the key exists in the other dictionary, and if not, add it.

foreach (var item in custom_settings)
{
    if (default_settings.ContainsKey(item.Key))
        default_settings[item.Key] = item.Value;
    else
        default_settings.Add(item.Key, item.Value);
}

I've done some basic LINQ queries, but I'm still working on learning the more advanced stuff. I've seen a few queries that will merge 2 dictionaries, but most involve grouping any element with duplicate keys, or only return a collection with just the duplicate keys/ Is there a LINQ query or expression that will mimic the behavior of the foreach loop I am using?

+10  A: 

Two points:

  1. LINQ isn't great for executing side effects. In this case, you're attempting to mutate an existing collection rather than execute a query, so I would shy away from a pure LINQ solution.
  2. The setter on the generic dictionary's indexer already has the effect of adding the key-value pair if the key doesn't exist, or overwriting the value if it does.

When you set the property value, if the key is in the Dictionary, the value associated with that key is replaced by the assigned value. If the key is not in the Dictionary, the key and value are added to the dictionary.

So your foreach loop is essentially equivalent to:

foreach (var item in custom_settings)
{
   default_settings[item.Key] = item.Value;
}

Now that's pretty terse already, so I don't think LINQ is going to help you all that much.

Ani
+1 for point #2 (http://msdn.microsoft.com/en-us/library/k7z0zy8k.aspx)
Brad
+1 for teaching me something i did not know. I'm relatively self taught with C# and never knew you could do that with dictionaries.
psubsee2003
@psubsee2003: Cheers. I'm pretty sure I used the same pattern as your code before I discovered it was redundant (by chance, was poking around with reflector).
Ani