在C#中使用LINQ比较字典

时间:2010-07-13 07:17:48

标签: c# linq

我需要比较两个词典并使用不匹配的项目更新另一个词典

两个词典就像

Dictionary<String, List<String>> DICTONE = new Dictionary<string, List<String>>();
Dictionary<string, List<String>> DICTTWO = new Dictionary<string, List<String>>();

内容

DICTONE["KEY1"]="A"
                "B"
                "C"

DICTONE["KEY2"]="D"
                "E"
                "F"

DICTTWO["KEY1"]="A"
                "B"
                "Z"

DICTTWO["KEY3"]="W"
                "X"
                "Y"

第三个字典有一个类实例作为值

Dictionary<String, MyClass> DICTRESULT = new Dictionary<string, MyClass>();

,班级就像

class MyClass
{
    public List<string> Additional = null;
        public List<string> Missing = null; 

    public MyClass()
        {
            Additional = new List<string>();
            Missing = new List<string>();
        }
        public MyClass(List<string> p_Additional, List<string> p_Missing)
        {
            Additional = p_Additional;
            Missing = p_Missing;
        }
}

场景是

  1. 如果在DICTONE中的项目而在DICTTWO中没有将项目添加到RESULTDICT中的MISSING列表
  2. 如果DICTTWO中的项目在DICTTON中而不在DICTTONE中,则将项目添加到RESULTDICT中的附加列表
  3. 预期答案是

    DICTRESULT["KEY1"]=ADDITIONAL LIST ---> "Z"
                       MISSING LIST    ---> "C"
    
    DICTRESULT["KEY2"]=ADDITIONAL LIST ---> ""
                       MISSING LIST    ---> "D"
                                            "E"
                                            "F"
    DICTRESULT["KEY3"]=ADDITIONAL LIST ---> ""
                       MISSING LIST    ---> "W"
                                            "X"
                                            "Y"
    

    有没有办法使用LINQ

    来做到这一点

1 个答案:

答案 0 :(得分:2)

嗯,这是一次尝试,假设firstsecond是有问题的词典。

var items = from key in first.Keys.Concat(second.Keys).Distinct()
            let firstList = first.GetValueOrDefault(key) ?? new List<string>()
            let secondList = second.GetValueOrDefault(key) ?? new List<string>()
            select new { Key = key,
                         Additional = secondList.Except(firstList),
                         Missing = firstList.Except(secondList) };
var result = items.ToDictionary(x => x.Key,
                                x => new MyClass(x.Additional, x.Missing));

这是完全未经测试的,请注意。我甚至没有尝试编译它。它还需要一个额外的扩展方法:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key)
{
    TValue value;
    dictionary.TryGetValue(key, out value)
    return value;
}