我正在尝试比较两个包含复杂对象的 C# 列表。我知道之前有人问过类似的问题,但这略有不同。 我完全遵循 MSDN 示例:https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx
public class ProductA
{
public string Name { get; set; }
public int Code { get; set; }
}
public class ProductComparer : IEqualityComparer<ProductA>
{
public bool Equals(ProductA x, ProductA y)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether the products' properties are equal.
return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
}
public int GetHashCode(ProductA obj)
{
//Get hash code for the Name field if it is not null.
int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = obj.Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
然后使用 Except 方法从列表中删除“apple”9
ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 },
new ProductA { Name = "orange", Code = 4 },
new ProductA { Name = "lemon", Code = 12 } };
ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } };
//Get all the elements from the first array //except for the elements from the second array.
IEnumerable<ProductA> except = fruits1.Except(fruits2);
foreach (var product in except)
Console.WriteLine(product.Name + " " + product.Code);
此代码应该产生以下输出: 橙子 4 柠檬 12
我的没有并打印出以下内容: 苹果 9 橙子 4 柠檬 12
最佳答案
MSDN 文档中似乎有错误:https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx
Except 方法调用应使用 IEqualityComparer:
//Get all the elements from the first array //except for the elements from the second array.
ProductComparer pc = new ProductComparer();
IEnumerable<ProductA> except = fruits1.Except(fruits2, pc);
关于c# - 使用 IEqualityComparer 比较两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844346/