假设我们有词典ld1和ld2的列表。两者都有一些共同的字典对象。假设字典对象“a”在两个列表中。我想合并词典列表,使得两个列表中的同一个对象在合并列表中只应出现一次。合并词典列表
Q
合并词典列表
0
A
回答
2
LINQ's .Union
应该很好地工作:
如果你需要一个List
,只需拨打ToList()
的结果。
1
如果要合并列表,Enumerable.Union
ld1.Union(ld2)
-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;
}
}
详细说明如下所示:
相关问题
- 1. 如何迭代词典列表并合并词典以形成新的较短的词典列表?
- 2. 合并字典的词典
- 3. Python字典列表合并
- 4. 合并嵌套词典
- 5. 合并两个词典
- 6. 在python中合并词典
- 7. 结合两个词典列表
- 8. 如何结合两个词典列表
- 9. 列表到词典列表
- 10. 将列表中的类似词典合并到一起
- 11. 在C#中包含列表的合并词典#
- 12. 更Python的方式来合并词典列表为一体?
- 13. 从词典列表
- 14. 遍历词典列表,创建词典的新列表
- 15. 将词典列表分成几个词典列表
- 16. 如何结合词典+列表,形成一个有序列表
- 17. 结合词典的两个词典(Python)
- 18. 转换词典的词典列表的字典
- 19. 列出很多词典VS词典与少数列表?
- 20. 合并元组和列表的列表,并创建字典
- 21. 比较列表与词典
- 22. Python的词典列表
- 23. Python列表到词典
- 24. 目录词典列表
- 25. 排序词典列表值
- 26. Python:列表到词典
- 27. Python-列表到词典
- 28. 循环词典列表
- 29. objective-c合并两个词典数组
- 30. 合并两个词典的键
相同的字典不会与Union一起重复,也不会重复存储在您的字典中。 – veblock
@ChibuezeOpata 5/9接受是[不是很差](http://meta.stackexchange.com/questions/88046/is-58-accept-rate-bad)。 – Blorgbeard