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.