如何改变CollectionViewSource的排序算法?事实上,我发现CollectionViewSource的排序算法并不稳定。我想在CollectionViewSource上使用一个稳定的算法。我怎么能这么做?
发布于 2014-07-29 12:48:15
我用一个定制的比较器得到了一个稳定的排序,但感觉像是一个大黑客.
正如本杰明建议的那样,我从集合中获取ListCollectionView,并使用自定义比较器设置它的CustomSort属性。唯一的区别是,在实例化集合时,我将集合传递给比较器。
private void Sorting(IEnumerable collection)
{
var view = CollectionViewSource.GetDefaultView(collection) as ListCollectionView;
if (view != null)
{
view.CustomSort = new StableComparer(collection);
}
}然后,在自定义比较器中,我使用比较方法中的集合,以便在比较返回零(它们是相同的或具有相同的值)时返回项索引。
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属性保持更新。或者支持两种方向。
但正如我所说,我认为这个想法是明确的,尽管有些刺耳。
发布于 2014-07-23 07:56:14
您可能需要查看如何实现自定义排序逻辑。
简而言之,把你的比较者设置成这样:
private void Sort(object sender, RoutedEventArgs args)
{
BlogPosts posts = (BlogPosts)(this.Resources["posts"]);
ListCollectionView lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(posts));
lcv.CustomSort = new SortPosts();
}并以如下方式实施:
public class SortPosts : IComparer
{
public int Compare(object x, object y)
{
(…)
}
}https://stackoverflow.com/questions/24904722
复制相似问题