我有以下方法来比较任何给定复杂类型的两个集合。在执行Sequence Equal操作之前,我需要使用要比较的类型的给定属性对两个集合进行排序,以确保对象的顺序相同。
public static bool CompareCollections<T>(IEnumerable<T> expectedCollection, IEnumerable<T> actualCollection,Func<T,string> selector)
{
if (expectedCollection.Count() != actualCollection.Count())
{
return false;
}
expectedCollection.OrderBy(selector).ToList();
actualCollection.OrderBy(selector).ToList();
return expectedCollection.SequenceEqual(actualCollection, new TypeComparer<T>());
}
我正在调用以下方法
CompareCollections(first,second,x => x.ID)
第一个和第二个集合如下所示,注意两个集合具有相同的两个对象,但第二个集合的项目顺序相反,我希望OrderBy方法在比较之前对其进行排序平等。但它没有像我预期的那样排序
var first = new List<Fee>()
{
new Fee
{
ID = "00001",
BaseFee = "3.50"
},
new Fee
{
ID = "00002",
BaseFee = "5.50"
}
};
var second = new List<Fee>()
{
new Fee
{
ID = "00002",
BaseFee = "5.50"
},
new Fee
{
ID = "00001",
BaseFee = "3.50"
}
};
答案 0 :(得分:2)
您需要将OrderBy().ToList()
的结果分配到新的局部变量中。 OrderBy
返回有序序列,它不会对传入的序列进行就地排序。因此:
var sortedExpectedCollection = expectedCollection.OrderBy(selector);
var sortedActualCollection = actualCollection.OrderBy(selector);
return sortedExpectedCollection.SequenceEqual(sortedActualCollection , new TypeComparer<T>());
答案 1 :(得分:0)
您可以这样做:
public static bool CompareCollections<T>(IEnumerable<T> expectedCollection, IEnumerable<T> actualCollection,
Func<T, string> selector)
{
var expectedAsList = expectedCollection.OrderBy(selector).ToList();
var actualAsList = actualCollection.OrderBy(selector).ToList();
return expectedAsList.Count == actualAsList.Count &&
!expectedAsList.Where((t, i) => !t.Equals(actualAsList[i])).Any();
}
答案 2 :(得分:0)
expectedCollection = expectedCollection.OrderBy(selector).ToList();
actualCollection = actualCollection.OrderBy(selector).ToList();
如果排序是问题,只需将值分配给列表并进行比较。