ListCollectionView CustomSort 2 条件
ListCollectionView CustomSort 2 conditions
我的 ViewModel 中有一个 ListCollectionView,我将它绑定到一个 ListBox。假设我有一个字符串集合,我首先想按字符串长度对它们进行排序,然后按字母顺序排序。我应该怎么做?
目前,我通过实现自己的 IComparer class 设法使用 CustomSort 按长度对它进行排序 class,但是我该怎么做才能使具有相同长度的字符串也按字母顺序排列。
您可以轻松地使用 LINQ 来做到这一点:
List<string> list = GetTheStringsFromSomewhere();
List<string> ordered = list.OrderBy(p => p.Length).ThenBy(p => p).ToList();
编辑:
您在评论中提到了 CustomSort
and SortDescription
。
我认为(未经测试)您应该能够通过滚动自己的比较器来获得相同的结果:
public class ByLengthAndAlphabeticallyOrderComparer : IComparer
{
int IComparer.Compare(Object x, Object y)
{
var stringX = x as string;
var stringY = y as string;
int lengthDiff = stringX.Length - stringY.Length;
if (lengthDiff !=)
{
return lengthDiff < 0 ? -1 : 1; // maybe the other way around -> untested ;)
}
return stringX.Compare(stringY);
}
}
用法:
_yourListViewControl.CustomSort = new ByLengthAndAlphabeticallyOrderComparer();
我的 ViewModel 中有一个 ListCollectionView,我将它绑定到一个 ListBox。假设我有一个字符串集合,我首先想按字符串长度对它们进行排序,然后按字母顺序排序。我应该怎么做?
目前,我通过实现自己的 IComparer class 设法使用 CustomSort 按长度对它进行排序 class,但是我该怎么做才能使具有相同长度的字符串也按字母顺序排列。
您可以轻松地使用 LINQ 来做到这一点:
List<string> list = GetTheStringsFromSomewhere();
List<string> ordered = list.OrderBy(p => p.Length).ThenBy(p => p).ToList();
编辑:
您在评论中提到了 CustomSort
and SortDescription
。
我认为(未经测试)您应该能够通过滚动自己的比较器来获得相同的结果:
public class ByLengthAndAlphabeticallyOrderComparer : IComparer
{
int IComparer.Compare(Object x, Object y)
{
var stringX = x as string;
var stringY = y as string;
int lengthDiff = stringX.Length - stringY.Length;
if (lengthDiff !=)
{
return lengthDiff < 0 ? -1 : 1; // maybe the other way around -> untested ;)
}
return stringX.Compare(stringY);
}
}
用法:
_yourListViewControl.CustomSort = new ByLengthAndAlphabeticallyOrderComparer();