0

我的 ViewModel 中有一个 ListCollectionView,我将它绑定到一个 ListBox。假设我有一个字符串集合,我首先要按字符串长度对它们进行排序,然后按字母顺序。我该怎么做?

目前,我通过实现我自己的 IComparer 类来使用 CustomSort 按长度对其进行排序,但是我该如何做到这一点,以便对于具有相同长度的字符串也按字母顺序排列。

4

1 回答 1

3

您可以轻松地使用 LINQ 来做到这一点:

List<string> list = GetTheStringsFromSomewhere();
List<string> ordered = list.OrderBy(p => p.Length).ThenBy(p => p).ToList();

编辑:

你在评论中提到CustomSortSortDescription。我认为(未经测试)您应该能够通过滚动自己的比较器来获得相同的结果:

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();
于 2016-05-17T09:01:55.390 回答