假设我们有字典 ld1 和 ld2 的列表。两者都有一些共同的字典对象。假设字典对象“a”在两个列表中。我想合并字典列表,这样相同的对象在两个列表中它应该只在合并列表中出现一次。
问问题
1473 次
4 回答
2
于 2012-07-05T03:45:29.603 回答
1
如果你想合并列表,Enumerable.Union
ld1.Union(ld2)
于 2012-07-05T03:51:53.757 回答
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;
}
}
详细解释见以下链接:
于 2012-07-05T04:53:13.593 回答
-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,“五”)。
于 2012-07-05T04:13:50.570 回答