我有一个通用的
List<MyClass>
假设 MyClass
有一个名为 InvoiceNumber
的属性,其中包含以下值:
200906/1
200906/2
..
200906/10
200906/11
200906/12
我的列表绑定到一个
BindingList<T>
它支持使用LINQ进行排序:
protected override void ApplySortCore(
PropertyDescriptor property, ListSortDirection direction)
{
_sortProperty = property;
_sortDirection = direction;
var items = this.Items;
switch (direction)
{
case ListSortDirection.Ascending:
items = items.OrderByDescending(x => property.GetValue(x)).ToList();
break;
case ListSortDirection.Descending:
items = items.OrderByDescending(x => property.GetValue(x)).ToList();
break;
}
this.Items = items;
}
然而默认的比较器按照以下顺序排序(如预期):
200906/1
200906/10
200906/11
200906/12
200906/2
在这种情况下,这很不好。
现在我想要使用自己的IComparer<T>
进行排序。它看起来像这样:
public class MyComparer : IComparer<Object>
{
public int Compare(Object stringA, Object stringB)
{
String[] valueA = stringA.ToString().Split('/');
String[] valueB = stringB.ToString().Split('/');
if(valueA .Length != 2 || valueB .Length != 2)
return String.Compare(stringA.ToString(), stringB.ToString());
if (valueA[0] == valueB[0])
{
return String.Compare(valueA[1], valueB[1]);
}
else
{
return String.Compare(valueA[0], valueB[0]);
}
}
}
并且修改了ApplySortCore
代码,以使用这个IComparer
:
case ListSortDirection.Ascending:
MyComparer comparer = new MyComparer();
items = items.OrderByDescending(
x => property.GetValue(x), comparer).ToList();
break;
当我调试我的代码时,我看到MyComparer.Compare(object, object)
被多次调用,并且为比较方法返回正确的值(-1、0、1)。但是我的列表仍然以“错误”的方式排序。我错过了什么吗?我一点头绪也没有。