【问题标题】:ObservableCollection Sort MethodObservableCollection 排序方法
【发布时间】:2018-09-25 15:06:26
【问题描述】:

我正在尝试使用扩展方法对 ObservableCollection 进行排序。

我将这篇文章用作参考:https://stackoverflow.com/a/16344936/1357553

这是我的代码:

public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable<T>
{
    List<T> sorted = collection.OrderBy(x => x).ToList();
    for (int newIndex = 0; newIndex < sorted.Count(); newIndex++)
    {
        int oldIndex = collection.IndexOf(sorted[newIndex]);
        if (oldIndex != newIndex)
            collection.Move(oldIndex, newIndex);
    }
}

所以,当我调用这个方法时,我遇到了一个异常:

ObservableCollection<myDataModel> AllTasks = new ObservableCollection<myDataModel>();
//fill AllTasks 
this.AllTasks.Sort();

例外:

"An item with the same key has already been added."

异常发生在我调用 Move() 方法时。

有趣的是,当我对“字符串”而不是“myDataModel”使用相同的方法时,它可以正常工作。我用谷歌搜索了一遍,我找不到任何关于这个异常的信息。 “myDataModel”的实现似乎有问题。

编辑:

myDataModel 的实现很普通。

public class myDataModel : IComparer<myDataModel >, IComparable<myDataModel >
{
    //other stuff

    public bool Equals(myDataModel other)
    {
        //equals implementation
    }


    #region IComparer, IComparable
    public int Compare(MainPlanTGanttTaskViewModel t1, MainPlanTGanttTaskViewModel t2)
    {
        return t1.CompareTo(t2);
    }

    public int CompareTo(MainPlanTGanttTaskViewModel other)
    {
        if (this.Start.CompareTo(other.Start) != 0) return this.Start.CompareTo(other.Start);
        else
        {
            return this.SapCode.CompareTo(other.SapCode);
        }
    }
    #endregion

}

谁能帮帮我?

【问题讨论】:

  • 嗯...myDataModel 的实现是什么? Equals()、GetHashCode() 之类的……
  • ““myDataModel”实现似乎有问题。”,所以..您想向我们展示您的实现可能有问题吗?
  • 无法按 OrderBy 进行排序?
  • 您没有对 observablecollection 进行排序,而是查看了 CollectionViewSource 吗?它具有视图所需的大部分功能(如排序和过滤),但保持初始集合不变。
  • 你可能想看看这个例子 - blogs.msdn.com/b/priozersk/archive/2010/05/26/…

标签: c# sorting observablecollection


【解决方案1】:

我正在使用以下代码对 Collection 进行排序:

ConceptItems = new ObservableCollection<DataConcept>(ConceptItems.OrderBy(i => i.DateColumn));

简单易行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2011-08-13
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多