首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CollectionViewSource排序算法

CollectionViewSource排序算法
EN

Stack Overflow用户
提问于 2014-07-23 07:51:09
回答 2查看 843关注 0票数 1

如何改变CollectionViewSource的排序算法?事实上,我发现CollectionViewSource的排序算法并不稳定。我想在CollectionViewSource上使用一个稳定的算法。我怎么能这么做?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-29 12:48:15

我用一个定制的比较器得到了一个稳定的排序,但感觉像是一个大黑客.

正如本杰明建议的那样,我从集合中获取ListCollectionView,并使用自定义比较器设置它的CustomSort属性。唯一的区别是,在实例化集合时,我将集合传递给比较器。

代码语言:javascript
复制
private void Sorting(IEnumerable collection)
{
    var view = CollectionViewSource.GetDefaultView(collection) as ListCollectionView;

    if (view != null)
    {
        view.CustomSort = new StableComparer(collection);
    }
}

然后,在自定义比较器中,我使用比较方法中的集合,以便在比较返回零(它们是相同的或具有相同的值)时返回项索引。

代码语言:javascript
复制
public class StableComparer : IComparer
{
    public IEnumerable Collection { get; set; }

    public StableComparer(IEnumerable collection)
    {
        Collection = collection;
    }

    public int Compare(object x, object y)
    {
        IComparable x_Comparable = x as IComparable;
        IComparable y_Comparable = y as IComparable;

        if (x_Comparable != null && y_Comparable != null)
        {
            var comparison = x_Comparable.CompareTo(y_Comparable);

            // A zero value means x and y are equivalent for sorting, and they could
            //  be rearranged by an unstable sorting algorithm
            if (comparison == 0 && Collection != null)
            {
                // IndexOf is an extension method for IEnumerable (not included)
                var x_Index = Collection.IndexOf(x);
                var y_Index = Collection.IndexOf(y);

                // By comparing their indexes in the original collection, we get to
                //  preserve their relative order
                if (x_Index != -1 && y_Index != -1)
                    comparison = x_Index.CompareTo(y_Index);
            }

            return comparison;
        }

        return 0;
    }
}

我还在测试这个,所以我不能保证这会一直有效.例如,一个问题是使比较器内的Collection属性保持更新。或者支持两种方向。

但正如我所说,我认为这个想法是明确的,尽管有些刺耳。

票数 4
EN

Stack Overflow用户

发布于 2014-07-23 07:56:14

您可能需要查看如何实现自定义排序逻辑

简而言之,把你的比较者设置成这样:

代码语言:javascript
复制
private void Sort(object sender, RoutedEventArgs args)
{
    BlogPosts posts = (BlogPosts)(this.Resources["posts"]);
    ListCollectionView lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(posts));
    lcv.CustomSort = new SortPosts();
}

并以如下方式实施:

代码语言:javascript
复制
public class SortPosts : IComparer
{
    public int Compare(object x, object y)
    {
        (…)
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24904722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档