c# - 使用 IEqualityComparer 比较两个列表

标签 c#

我正在尝试比较两个包含复杂对象的 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/

相关文章:

c# - 使用 InMemoryDatabase 和 Identity 列进行测试,如何处理?

c# - 如何调整颜色的亮度?

c# - 多个应用程序如何监听同一个端口(80)?

c# - ASP.NET Identity 中的零星应用程序死锁

c# - 强制控制宽度或高度?

c# - 值类型不同的 WebAPI Controller 方法

c# - 将 XML 属性注入(inject)序列化

c# - 仅基于返回类型重载

c# - 运算符 '??' 不能应用于类型 'int' 和 'int' 的操作数

c# - 无法使用带有 Autofac 的 AutoMapper 4.2 解析 AutoMapper.IMapper