我有以下方法来比较任何给定复杂类型的两个集合。在执行序列相等操作之前,我需要使用要比较的类型的给定属性对两个集合进行排序,以确保对象的顺序相同。
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"
}
};
最佳答案
您需要将 OrderBy().ToList()
的结果分配给一个新的局部变量。 OrderBy
返回一个有序序列,它不会就地对传入序列进行排序。因此:
var sortedExpectedCollection = expectedCollection.OrderBy(selector);
var sortedActualCollection = actualCollection.OrderBy(selector);
return sortedExpectedCollection.SequenceEqual(sortedActualCollection , new TypeComparer<T>());
关于c# - 使用属性对两个复杂类型的泛型集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667208/