简体   繁体   English

比较字典 <string,List<object> &gt;

[英]Compare Dictionary<string,List<object>>

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. 我正在将两个字典(dic1和dic2)与从dic2获取键匹配但值不匹配或dic2中缺少键的规则进行比较。
Don't need to iterate through dic2 for missing/different values in dic1. 对于dic1中缺少/不同的值,不需要遍历dic2。

Below code is working ok I would like to know is there any better way using .NET 2.0 (NO LINQ) . 下面的代码可以正常工作,我想知道使用.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 选项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 选项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]);
    }
});

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. 如果在访问dic2时使用TryGetValue,则可以使用这两个选项来加快速度,因此您只需执行一次键查找。

Your first option looks simpler and possibly faster, i'd go with that. 您的第一个选择看起来更简单,甚至可能更快,我会同意的。 Cheers 干杯

I would use Option 1. Here's a variation on it using TryGetValue instead of looking up dic2[var.Key] so many times: 我将使用选项1。这是使用TryGetValue的一种变体,而不是多次查找dic2[var.Key]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM