I ran into a problem with IComparer
and System.Collections.Generic.List
when all items are considered equal:
If all items in the source list are considered equal, I would expect the "sorted" list to have exactly the same item order than the source list (i.e. remain unchanged).
However, I noticed that the item order in the sorted list is different.
For example, imagine I sort a list of person objects by first name:
Source list:
- John Miller
- John Smith
- John Doe
- John Williams
Result comparing the first name with IComparer
:
- John Williams
- John Smith
- John Miller
- John Doe
To reproduce:
public class AllTheSameComparer : IComparer<int>
{
public int Compare(int x, int y)
{
return 0; // all are equal
}
}
The following unit test will fail for more than 20 items:
[TestMethod]
public void testCompareSimple()
{
var numbers = new List<int>();
for (var i = 0; i < 2000; i++)
{
numbers.Add(i);
}
var fixture = new AllTheSameComparer();
numbers.Sort(fixture);
for (var i = 0; i < numbers.Count; i++)
{
var actual = numbers[i];
Assert.AreEqual(i, actual);
}
}
Is this expected behavior? Is there a way for me to keep the original item order of equal elements without having to compare a second object property?