Reputation: 411
I have an array of objects that I sort by type. Within that array is a set of objects of one type that are already in their preferred relative order. After the sort, these objects are grouped together, but no longer in the same order. I am using the sort a follows
Array.Sort(shapes, GetVisualComparer());
I have looked for a sort method that promises to preserve original order, but have found nothing.
I will note that I have a workaround, but it adds unnecessary confusion to the code, and does not address the general problem if it comes up in the future.
Upvotes: 2
Views: 290
Reputation: 6717
Make a copy of the original array. Then, make your comparer compare the original indexes of your elements if their type is equal.
I don't know on what you base your type sorting, but sorting by name, it would look somewhat like this:
public class TypeComparer : IComparer<Type>
{
public int Compare(Type x, Type y)
{
int result = StringComparer.InvariantCulture.Compare(x.Name, y.Name);
if (result == 0)
{
result = Array.IndexOf(originalArray, x).CompareTo(Array.IndexOf(originalArray, y));
}
return result;
}
}
Upvotes: 2
Reputation: 1557
The problem is that Array.Sort<T>(T[], IComparer<T>)
is not using a stable sort.
This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
You'll have to sort your array using some other method.
Upvotes: 2