blah blah blah is here! blah blah » Close

up0down
link

Why does order change when I sort elements by property that is the same in the every element?
This is my example:
public class MyClass
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public override string ToString()
{
return "Id = " + _id.ToString() + "\tName = " + _name.ToString();
}
}
public class SortByName : IComparer<MyClass>
{
int IComparer<MyClass>.Compare(MyClass x, MyClass y)
{
return x.Name.CompareTo(y.Name);
}
}
....
List<MyClass> list = new List<MyClass>();
MyClass obj = new MyClass();
obj.Id = 1;
obj.Name = "A";
list.Add(obj);
obj = new MyClass();
obj.Id = 2;
obj.Name = "A";
list.Add(obj);
obj = new MyClass();
obj.Id = 3;
obj.Name = "A";
list.Add(obj);
Console.WriteLine("List before sort");
foreach (MyClass o in list)
Console.WriteLine(o.ToString());
SortByName byName = new SortByName();
list.Sort(byName);
Console.WriteLine("\nList after first sort");
foreach (MyClass o in list)
Console.WriteLine(o.ToString());
list.Sort(byName);
Console.WriteLine("\nList after second sort");
foreach (MyClass o in list)
Console.WriteLine(o.ToString());
Console.Read();
.....
After first sort order is changed, after second sort order is original.
What do I have to do to avoid this strange behavior? I don`t want change order if I sort by property that is the same in every element. I also don`t want sort to times because I have a large list and it can cause blink on the screen.

last answered 9 months ago

1 answers

up0down
link

The List<T>.Sort() method uses the Quick Sort algorithm to do the sorting which is fast but 'unstable' in the sense that it does not necessarily preserve the order of items which sort as equal.
To guarantee that order will be preserved, you need to use a different algorithm such as an Insertion Sort. <a target="_new" href="http://www.devtopics.com/c-stable-sort/">This article</a> shows how to write one for a given class.
Of course, if your list is large, then whether or not this algorithm will be fast enough remains to be seen.

up0down
link

Thank you very much!

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback