2010-07-13 112 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; 
}