Compare Dictionary>

2019-07-12 05:09发布

问题:

I am comparing two dictionary(dic1 and dic2) with rule that get values from dic2 where key match but values does not match or key is missing in dic2.
Don’t need to iterate through dic2 for missing/different values in dic1.

Below code is working ok I would like to know is there any better way using .NET 2.0 (NO LINQ) .

if optimization is require which option is better?

Dictionary<string,List<foo>> dic1 = new Dictionary<string,List<foo>>();
Dictionary<string,List<foo>> dic2 = new Dictionary<string,List<foo>>();

dic1.add("1", new foo("a"));
dic1.add("2", new foo("b"));
dic1.add("3", new foo("c"));
dic1.add("3", new foo("c1"));
dic1.add("4", new foo("d"));

dic2.add("1", new foo("a"));
dic2.add("2", new foo("b1"));
dic2.add("3", new foo("c"));
dic2.add("3", new foo("c2"));

//I write code which allow duplicate key in dictionary 

Option 1

foreach (KeyValuePair<string, List<foo>> var in dic1)
{
    if (dic2.ContainsKey(var.Key))
    {
        List<foo> tempList = var.Value.FindAll(delegate(foo s)
        {
            return !dic2[var.Key].Contains(s);
        });
        result.AddRange(tempList);
    }
    else
    {
        result.Add(var.Value);
    }

}

Option 2

List<string> list1key = new List<string>(dic1.Keys);

list1key.ForEach(delegate(string key)
{
    if (dic2.ContainsKey(key))
    {
        List<foo> tempList = dic1[key].FindAll(delegate(foos)
           {
               return !dic2[key].Contains(s);
           });
        result.AddRange(tempList);
    }
    else
    {
        result.AddRange(dic1[key]);
    }
});

回答1:

You can speed things up with either option if you use TryGetValue when accessing dic2, so you only have to do a key lookup once.

Your first option looks simpler and possibly faster, i'd go with that. Cheers



回答2:

I would use Option 1. Here's a variation on it using TryGetValue instead of looking up dic2[var.Key] so many times:

foreach (KeyValuePair<string, List<foo>> var in dic1) 
{
    List<foo> dic2val;
    if (dic2.TryGetValue(var.Key, out dic2val)) 
    { 
        List<foo> tempList = var.Value.FindAll(delegate(foo s) 
        { 
            return !dic2val.Contains(s); 
        }); 
        result.AddRange(tempList); 
    } 
    else 
    { 
        result.Add(var.Value); 
    } 
} 


标签: c# delegates