I am trying to sort a ObservableCollection using a extension method.
I'm using as reference this post: https://stackoverflow.com/a/16344936/1357553
Here is my code:
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);
}
}
So, when I call this method using I got an exception:
ObservableCollection<myDataModel> AllTasks = new ObservableCollection<myDataModel>();
//fill AllTasks
this.AllTasks.Sort();
Exception:
"An item with the same key has already been added."
The exception occurs in when I call the Move() method.
The funny thing is that, when I use the same method with a "string" instead of "myDataModel", it works fine. I have googled all over and I could not find anything about this exception. It looks like there is something wrong with "myDataModel" implementation.
EDIT:
The implementation of myDataModel is quite ordinary.
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
}
Can anyone give me some help?