gpt4 book ai didi

c# - CollectionViewSource排序算法

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:11 24 4
gpt4 key购买 nike

如何改变CollectionViewSource的排序算法?其实我发现CollectionViewSource的排序算法并不稳定。我想在 CollectionViewSource 上使用稳定的算法。我该怎么做?

最佳答案

我已经设法使用自定义比较器进行了稳定的排序,但感觉有点像一个大 hack...

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

private void Sorting(IEnumerable collection)
{
var view = CollectionViewSource.GetDefaultView(collection) as ListCollectionView;

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

然后,在我的自定义 Comparer 中,我在 Compare 方法中使用集合只是为了在比较返回零时回退到项目索引(它们相同或具有相同的值)。

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;
}
}

我仍在对此进行测试,因此我不能保证它会一直有效...例如,一个问题是保持 Comparer 中的 Collection 属性更新。或者支持两种排序方向。

但我认为这个想法很清楚,尽管像我说的那样有点老套。

关于c# - CollectionViewSource排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com