我有一个通用的使用自己的IComparer <T>使用LINQ的OrderBy
List<MyClass>
其中MyClass
具有包含值如属性InvoiceNumber
:
一分之二十零万零九百零六
二分之二十零万零九百零六
..
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/10
200906/11
200906/1 2
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)用于比较方法。
但我的名单仍然排序“错误”的方式。我错过了什么吗?我没有任何线索。
对不起,我shortend代码一点。在我原来的代码中,我做this.Items =项目; (如果没有,它不会排序)但int转换的作品(我一定是盲目的||愚蠢的错过了)。 Thx非常。 – 2009-06-12 11:06:15