2010-07-13 92 views
2

我需要比较两个库和更新具有无可比拟的项目在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
  2. 的项目添加到失踪名单如果一个项目在DICTTWO中而不是在DICTTONE中将该项目添加到RESULTDICT中的附加列表中

预期的答案是

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

+0

看起来像功课,你可以显示你已经做了什么? – 2010-07-13 07:27:53

+0

并不多,他已经问过一个非常类似的问题http://stackoverflow.com/questions/3226123/how-to-compare-two-xml-files-in-c-using-xml-to-linq – 2010-07-13 07:31:36

回答

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