开发者

Simplest way to make SortableBindingList use a stable sort

There is an example of how to modify SortableBindingList to use a stable sort. However, there is an updated version of SortableBindingList. What is the best way to modify th开发者_JAVA百科is new version to use a stable sort? I think I would want a flag on the SortableBindingList to let the user of the SortableBindingList decide if they want to use (slower) stable sort or (faster) default sort.

Thanks


You can solve this problem by writing a stable sort extension method for List<T>:

public static class ListExtensions
{
    public static void StableSort<T>(this List<T> list, IComparer<T> comparer)
    {
        var pairs = list.Select((value, index) => Tuple.Create(value, index)).ToList();
        pairs.Sort((x, y) =>
            {
                int result = comparer.Compare(x.Item1, y.Item1);
                return result != 0 ? result : x.Item2 - y.Item2;
            });
        list.Clear();
        list.AddRange(pairs.Select(key => key.Item1));
    }
}

and then in the new version of SortableBindingList change this line:

itemsList.Sort(comparer);

to:

itemsList.StableSort(comparer);

This works by using the unstable sort supplemented with a secondary key on the item index within the list. Since this version doesn't use the pathologically slow insertion sort to achieve a stable sort, it should be fast enough for general use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜