C# 使用IEqualityComparer比较两个列表

C# 使用IEqualityComparer比较两个列表,c#,C#,我试图比较两个包含复杂对象的c#列表。我知道以前也有人问过类似的问题,但情况略有不同。 我完全遵循MSDN示例: 公共类产品a { 公共字符串名称{get;set;} 公共整数代码{get;set;} } 公共类产品比较程序:IEqualityComparer { 公共布尔等于(ProductA x,ProductA y) { //检查对象是否为同一对象。 if(Object.ReferenceEquals(x,y))返回true; //检查产品的属性是否相等。 返回x!=null&&y!=n

我试图比较两个包含复杂对象的c#列表。我知道以前也有人问过类似的问题,但情况略有不同。 我完全遵循MSDN示例:

公共类产品a
{ 
公共字符串名称{get;set;}
公共整数代码{get;set;}
}
公共类产品比较程序:IEqualityComparer
{
公共布尔等于(ProductA x,ProductA y)
{
//检查对象是否为同一对象。
if(Object.ReferenceEquals(x,y))返回true;
//检查产品的属性是否相等。
返回x!=null&&y!=null&&x.Code.Equals(y.Code)&&x.Name.Equals(y.Name);
}
public int GetHashCode(ProductA obj)
{
//如果名称字段不为null,则获取其哈希代码。
int-hashProductName=obj.Name==null?0:obj.Name.GetHashCode();
//获取代码字段的哈希代码。
int hashProductCode=obj.Code.GetHashCode();
//计算产品的哈希代码。
返回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);
ProductA[]fruits1={newproducta{Name=“apple”,code=9},
新产品a{Name=“orange”,代码=4},
新产品a{Name=“lemon”,代码=12};
ProductA[]fruits2={newproducta{Name=“apple”,Code=9};
//获取第一个数组//中的所有元素,第二个数组中的元素除外。
IEnumerable except=结果1.除外(结果2);
foreach(除外的var产品)
Console.WriteLine(product.Name+“”+product.Code);
此代码应产生以下输出: 橙4柠檬12

我的没有,并打印出以下内容:
apple 9 orange 4 lemon 12

MSDN文档中似乎有错误:

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);
//获取第一个数组中的所有元素//第二个数组中的元素除外。
ProductComparer pc=新ProductComparer();
IEnumerable except=水果1.except(水果2,pc);

文档在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);