【问题标题】:ListCollectionView CustomSort 2 conditionsListCollectionView CustomSort 2 条件
【发布时间】:2016-05-17 08:59:26
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf sorting listcollectionview


    【解决方案1】:

    您可以轻松地使用 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();
    

    【讨论】:

    • 我实际上希望使用 SortDescription 或 CustomSort,这样我就不必在集合更改时总是对其进行排序。
    • 我已经更新了我的主帖。我有一个绑定到 ListBox ItemsSource 的 ListCollectionView。我可以将项目拖入和拖出 ListBox,因此集合可以更改,并且每当集合更改时,我希望它按我想要的方式排序。如果我使用 LINQ,我总是需要在集合发生变化时对其进行重新排序。那么有什么方法可以使用 SortDescription 或 CustomSort,以便 UI 可以在集合更改时自动为我排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    相关资源
    最近更新 更多