创建的IEqualityComparer<&IEnumerable的LT; T>> [英] Creating a IEqualityComparer<IEnumerable<T>>
问题描述
我使用的xUnit,它并没有办法来确定是否2 的IEnumerable< T>
都是平等的,如果 T
是自定义类型。
I'm using xUnit and it doesn't have a way to determine if 2 IEnumerable<T>
are equal if T
is custom type.
我试过使用 LINQ SequenceEqual
但同样作为实例 T
是不同的这一返回false;
I've tried using LINQ SequenceEqual
but again as the instances of T
are different this returns false;
下面是一个基本的测试非工作的IEqualityComparer
Here is a basic test with a non-working IEqualityComparer
[Fact]
public void FactMethodName()
{
var one = new[] { new KeywordSchedule() { Id = 1 } };
var two = new[] { new KeywordSchedule() { Id = 1 } };
Assert.Equal(one, two, new KeywordScheduleComparer());
}
public class KeywordScheduleComparer : IEqualityComparer<IEnumerable<KeywordSchedule>>
{
public bool Equals(IEnumerable<KeywordSchedule> x, IEnumerable<KeywordSchedule> y)
{
return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y));
}
public int GetHashCode(IEnumerable<KeywordSchedule> obj)
{
if (obj == null)
return 0;
return unchecked(obj.Select(e => e.GetHashCode()).Aggregate(0, (a, b) => a + b)); // BAD
}
}
我在集成使用此测试,所以我在一开始插入从IEnumerable数据转换成一个数据块,然后叫我SUT从数据库检索数据并进行比较。
I'm using this in an integration test, so I insert data from a IEnumerable into a DB at the start, then call my SUT to retrieve data from DB and compare.
如果你能帮助我得到一个!收集比较工作,我会很感激的。
If you can help me get a collection comparison working I'd appreciate it!
推荐答案
我只是验证了该工作正常xUnit.net 1.9.2:
I just verified that this works fine with xUnit.net 1.9.2:
public class MyClass
{
public int ID { get; set; }
public string Name { get; set; }
}
public class MyClassComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass x, MyClass y)
{
return x.ID == y.ID;
}
public int GetHashCode(MyClass obj)
{
return obj.ID.GetHashCode();
}
}
public class ExampleTest
{
[Fact]
public void TestForEquality()
{
var obj1 = new MyClass { ID = 42, Name = "Brad" };
var obj2 = new MyClass { ID = 42, Name = "Joe" };
Assert.Equal(new[] { obj1 }, new[] { obj2 }, new MyClassComparer());
}
}
所以,我不是100%清楚为什么你需要额外的比较器。只是单一的比较器就足够了。
So I'm not 100% clear why you need the extra comparer. Just the single comparer should be sufficient.
这篇关于创建的IEqualityComparer<&IEnumerable的LT; T>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!