2012-07-05 98 views
0

假設我們有詞典ld1和ld2的列表。兩者都有一些共同的字典對象。假設字典對象「a」在兩個列表中。我想合併詞典列表,使得兩個列表中的同一個對象在合併列表中只應出現一次。合併詞典列表

+0

相同的字典不會與Union一起重複,也不會重複存儲在您的字典中。 – veblock

+2

@ChibuezeOpata 5/9接受是[不是很差](http://meta.stackexchange.com/questions/88046/is-58-accept-rate-bad)。 – Blorgbeard

回答

2

LINQ's .Union應該很好地工作:

如果你需要一個List,只需撥打ToList()的結果。

-1
Dictionary<int, string> dic1 = new Dictionary<int, string>(); 
dic1.Add(1, "One"); 
dic1.Add(2, "Two"); 
dic1.Add(3, "Three"); 
dic1.Add(4, "Four"); 
dic1.Add(5, "Five"); 

Dictionary<int, string> dic2 = new Dictionary<int, string>(); 
dic2.Add(5, "Five"); 
dic2.Add(6, "Six"); 
dic2.Add(7, "Seven"); 
dic2.Add(8, "Eight"); 

Dictionary<int, string> dic3 = new Dictionary<int, string>(); 
dic3 = dic1.Union(dic2).ToDictionary(s => s.Key, s => s.Value); 

結果dic3具有重複鍵值八個值(5, 「五」)中刪除。

0

如果您正在使用自定義對象或類,則簡單的enumerable.Union將不起作用。

您必須創建自定義比較器。

爲此創建一個新的類,它實現的IEqualityComparer然後使用此如下

oneList.Union(twoList,customComparer)

一些代碼示例如下所示:

public class Product 
{ 
    public string Name { get; set; } 
    public int Code { get; set; } 
} 

// Custom comparer for the Product class 
class ProductComparer : IEqualityComparer<Product> 
{ 
    // Products are equal if their names and product numbers are equal. 
    public bool Equals(Product x, Product y) 
    { 

     //Check whether the compared objects reference the same data. 
     if (Object.ReferenceEquals(x, y)) return true; 

     //Check whether any of the compared objects is null. 
     if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 
      return false; 

     //Check whether the products' properties are equal. 
     return x.Code == y.Code && x.Name == y.Name; 
    } 

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects. 

    public int GetHashCode(Product product) 
    { 
     //Check whether the object is null 
     if (Object.ReferenceEquals(product, null)) return 0; 

     //Get hash code for the Name field if it is not null. 
     int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); 

     //Get hash code for the Code field. 
     int hashProductCode = product.Code.GetHashCode(); 

     //Calculate the hash code for the product. 
     return hashProductName^hashProductCode; 
    } 

} 

詳細說明如下所示:

http://msdn.microsoft.com/en-us/library/bb358407.aspx