如何排除属性,然后比较列表

本文关键字:然后 比较 列表 属性 何排除 排除 | 更新日期: 2023-09-27 18:28:40

在我的单元测试方法中创建了两个对象列表,

即一个是CCD_ 1,另一个是CCD_。

expectedValueList={a=1,b=2,c=3,d=4}
actualvalueList={d=4,b=2,c=3,a=1}

我用比较

CollectionAssert.AreEqual(expectedValueList, actualvalueList);

我需要从两个列表中排除"c" property,然后我想比较两个列表是否相等?

如何排除属性,然后比较列表

假设两个列表都是List<CustomType>,其中CustomType有两个属性。现在,您需要一种方法来比较两个列表,但忽略一个值。

如果订单很重要,我会使用Enumerable.SequenceEqual:

var expectedWithoutC = expectedValueList.Where(t => t.Name != "c");
var actualWithoutC = actualvalueList.Where(t => t.Name != "c");
bool bothEqual = expectedWithoutC.SequenceEqual(actualWithoutC); 

请注意,如果我的假设是正确的,您需要覆盖Equals(和GetHashCode)。否则,SequenceEqual将仅比较参考相等性。

假设expectedValueList0是Dictionary<string, int>

var expectedValueList = new SortedDictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 }, { "d", 4 } };
expectedValueList.Remove("c");
var actualValueList = new SortedDictionary<string, int> { { "d", 4 }, { "b", 2 }, { "c", 3 }, { "a", 1 } };
actualValueList.Remove("c");
// Will return false if the order is different.
CollectionAssert.AreEqual(expectedValueList, actualvalueList);