合并词典列表

时间:2012-07-05 03:43:33

标签: c#

假设我们有字典列表ld1和ld2。两者都有一些共同的字典对象。假设字典对象“a”在两个列表中。我想合并字典列表,这样两个列表中的同一个对象只能在合并列表中出现一次。

4 个答案:

答案 0 :(得分:2)

LINQ's .Union应该可以很好地运作:

oneList.Union(twoList)

如果您需要List,只需在结果上调用ToList()

答案 1 :(得分:1)

如果要合并列表,Enumerable.Union

ld1.Union(ld2)

答案 2 :(得分: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

答案 3 :(得分:-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,“Five”)。