Linq的Intersect不会调用GetHashCode

时间:2012-10-05 15:28:44

标签: c# linq

var resultList = list1.Intersect<XElement>(list2, new XElementComparer());

为什么我的XElementComparer的GetHashCode方法从未被调用过?

当我检查resultList的内容时,我看到:

System.Exeception object to set to an instance of an object

我的两个列表都有XElements。我错了什么?

2 个答案:

答案 0 :(得分:3)

Intersect扩展方法会返回IEnumerable<>,但在您开始枚举之前不会实际执行交集(例如,执行foreach,调用.ToList()等。) 。因此,我不希望比较器上的任何方法根据您给出的代码段进行调用,因为您没有枚举结果。

答案 1 :(得分:0)

我敢打赌,它正在调用GetHashCode 的实现,即实现(或Equals)抛出NullReferenceException。 我们能够真正回答您问题的唯一方法是为XElementComparer添加代码。

我运行了一个快速测试,产生了这个输出:

  

等于count = 1; GetHashCode count = 6

[Test]
public void X()
{
    var list1 = new List<Alpha> {new Alpha {Bravo = 1}, new Alpha {Bravo = 1}, new Alpha {Bravo = 2}};
    var list2 = new List<Alpha> { new Alpha { Bravo = 1 }, new Alpha { Bravo = 3 }, new Alpha { Bravo = 5 } };

    var alphaComparer = new AlphaComparer();

    Assert.AreEqual(1, list1.Intersect(list2, alphaComparer).Count());
    Console.WriteLine("Equals count = {0}; GetHashCode count = {1}", alphaComparer.EqualsCallCount, alphaComparer.GetHashCodeCallCount);
}

class Alpha
{
    public int Bravo { get; set; }
}

class AlphaComparer : IEqualityComparer<Alpha>
{
    public int EqualsCallCount { get; private set; }
    public int GetHashCodeCallCount { get; private set; }

    public bool Equals(Alpha x, Alpha y)
    {
        EqualsCallCount += 1;
        return x.Bravo.Equals(y.Bravo);
    }

    public int GetHashCode(Alpha obj)
    {
        GetHashCodeCallCount += 1;
        return obj.Bravo.GetHashCode();
    }