views:

70

answers:

1

Is there any way to get consistent results from Comparison when some of the sort items are the same? Do I just have to code up my own sort routine?

    public class Sorter
{
    public void SortIt()
    {
        var myData = new List<SortData>(3);
        myData.Add(new SortData { SortBy = 1, Data = "D1"});
        myData.Add(new SortData { SortBy = 1, Data = "D2" });
        myData.Add(new SortData { SortBy = 2, Data = "D3" });

        myData.Sort(new Comparison<SortData>((a, b) => a.SortBy.CompareTo(b.SortBy)));
        ShowResults(myData);
        myData.Sort(new Comparison<SortData>((a, b) => a.SortBy.CompareTo(b.SortBy)));
        ShowResults(myData);
        myData.Sort(new Comparison<SortData>((a, b) => a.SortBy.CompareTo(b.SortBy)));
        ShowResults(myData);
    }

    private void ShowResults(IEnumerable<SortData> myData)
    {
        foreach (var data in myData)
        {
            Console.WriteLine(data.SortBy + " " + data.Data);
        }
        Console.WriteLine("\n");
    }
}

public class SortData
{
    public int SortBy { get; set; }
    public string Data { get; set; }
}
enter code here

Now notice what the results are:

1 D2
1 D1
2 D3

1 D1
1 D2
2 D3

1 D2
1 D1
2 D3

I don't really care how the first two items are sorted as long as it's consistent and it's not! It keeps flip flopping.

+2  A: 

Basically yes : http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

This method uses Array..::.Sort, which uses the QuickSort algorithm. 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.

If you want to have a stable sort, look elsewhere or roll your own.

Johan Buret