当前位置: 代码迷 >> C# >> 关于IEqualityComparer,该如何解决
  详细解决方案

关于IEqualityComparer,该如何解决

热度:156   发布时间:2016-04-28 08:30:53.0
关于IEqualityComparer
情况是这样的,现在想对两个List进行比较,先分别记住listA、listB吧,存放的都是同一个自定义类的对象。若listA中的每一个对象,在listB中都有一个对象与它各成员值都相等,且对于listB中的每一个对象,在listA中都有一个对象与它各成员值都相等,则判定listA=listB。每个list都含有比较多的数据。我现在还没想到比较好的方法,找了半天的msdn上找到一段类似的代码,摘抄如下:
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;
    }
}
///////////////////////////////////////
ProductA[] storeA = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "orange", Code = 4 } };

ProductA[] storeB = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "orange", Code = 4 } };

bool equalAB = storeA.SequenceEqual(storeB);

Console.WriteLine("Equal? " + equalAB);

/*
    This code produces the following output:

    Equal? True
*/
原码:https://msdn.microsoft.com/zh-cn/library/bb348567.aspx

但我测试后,
bool equalAB = storeA.SequenceEqual(storeB);

equalAB返回的是false.这是怎么回事?

项目比较急,而且我对C#不熟,请各位路过的大神帮忙看看,感激不尽!
------解决思路----------------------
bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer());
  相关解决方案