2010-10-25 154 views
3

這是在C#2.0(無LINQ)中比較的正確方法。在C#2.0中比較兩個List <KeyValuePair <string,Object >>的正確方法

下面的代碼工作正常,但我認爲它不是比較好的方法。

 List<KeyValuePair<string, foo>> list1 = new List<KeyValuePair<string, foo>>(); 
     List<KeyValuePair<string, foo>> list2 = new List<KeyValuePair<string, foo>>(); 
     List<foo> diffList = new List<foo>(); 

     list1.Add(new KeyValuePair<string, foo>("1", new foo("1", new Cost(1.0))); 
     list1.Add(new KeyValuePair<string, foo>("2", new foo("2", new Cost(2.0))); 
     list1.Add(new KeyValuePair<string, foo>("3", new foo("3", new Cost(3.0))); 
     list1.Add(new KeyValuePair<string, foo>("5", new foo("5", new Cost(5.0))); 

     list2.Add(new KeyValuePair<string, foo>("1", new foo("1", new Cost(1.0)); 
     list2.Add(new KeyValuePair<string, foo>("2", new foo("2", new Cost(2.1))); 
     list2.Add(new KeyValuePair<string, foo>("4", new foo("4", new Cost(4.0)); 
     list2.Add(new KeyValuePair<string, foo>("6", new foo("6", new Cost(6.0))); 
     list2.Add(new KeyValuePair<string, foo>("7", new foo("7", new Cost(7.0))); 

     foreach (KeyValuePair<string, foo> pair1 in list1) 
     { 
      bool b = true; 
      foreach (KeyValuePair<string, foo> pair2 in list2) 
      { 
       if (pair2.Key == pair1.Key) 
       { 
        if (pair2.Value.Equals(pair1.Value)) 
        { 
         list2.Remove(pair2); 
         break; 
        } 
        else 
        { 
         diffList.Add(pair2.Value); 
         diffList.Add(pair1.Value); 
         list2.Remove(pair2); 
         b = false; 
         break; 
        } 
       } 
       else 
       { 

        diffList.Add(pair2.Value); 
        diffList.Add(pair1.Value); 
        list2.Remove(pair2); 
        b = false; 
        break; 
       } 
      } 
      if (list2.Count == 0 && b) 
      { 
       diffList.Add(pair1.Value); 
      } 
     } 
     foreach (KeyValuePair<string, foo> pair2 in list2) 
     { 
      diffList.Add(pair2.Value); 
     } 

回答

2

這將是更簡單,更快:

  1. 推兩個列表到字典(或擺在首位構建字典)。
  2. 迭代一個字典,查找另一個字典中的每個鍵,相應地添加差異條目。只添加正在迭代的詞典中的條目。
  3. 交換詞典並重復循環。
2

Marcelo是對的,KeyValuePairs的列表總是更好地表示爲字典,除非您希望因某種原因能夠擁有重複的鍵。

嘗試這樣:

var a = list1.ToDictionary(i => i.Key, i => i.Value); 
var b = list2.ToDictionary(i => i.Key, i => i.Value); 
var result = new List<foo>(); 

foreach (var entry in a) 
{ 
    if (b.ContainsKey(entry.Key) 
     && entry.Value != b[entry.Key]) 
    { 
     result.Add(entry.Value); 
     result.Add(b[entry.Key]); 
    } 
} 
foreach (var entry in b) 
{ 
    if (a.ContainsKey(entry.Key) 
     && entry.Value != a[entry.Key] 
     && !result.Contains(entry.Value)) 
    { 
     result.Add(entry.Value); 
     result.Add(a[entry.Key]); 
    } 
} 
相關問題