2012-07-05 58 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