Reputation: 1019
I am sorting a custom class as follows, which is sorted by FirstHalfPoints:
var firstHalfTables = new FirstHalfTableCollection();
firstHalfTables.PopulateForSeason(SeasonId);
firstHalfTables.Sort((t1, t2) => t1.FirstHalfPoints.CompareTo(t2.FirstHalfPoints));
firstHalfTables.Reverse();
FirstHalfTableRepeater.DataSource = firstHalfTables;
FirstHalfTableRepeater.DataBind();
I also need to sort by a two further fields 'GD' - Goal Difference and 'GF' - Goals For- after this initial sort by 'FirstHalfPoints'
So the finished collection will be sorted by FirstHalfPoints, then by GD, then by GF.
Can anyone help me out with multiple sorting?
Upvotes: 0
Views: 512
Reputation: 52270
you can use direct LINQ expressions: "OrderBy" and "ThenBy" too: MSDN Sorting Data
OR
you have to extent your comparison. You have to remember: a.CompareTo(b)
should return -1 if a is "smaller" than b, 0 if they are equal and +1 if a is "bigger" than b.
So try the following:
private void Compare(YourRow a, YourRow b)
{
let v = a.FirstHalfPoints.CompareTo(b.FirstHalfPoints);
if (v != 0) return v;
v = a.GD.CompareTo(b.GD);
if (v != 0) return v;
return a.GF.CompareTo(b.GF);
}
and call Sort
with this function.
Upvotes: 1
Reputation: 244757
You could use LINQ, which often makes the code more readable:
var firstHalfTables = new FirstHalfTableCollection();
firstHalfTables.PopulateForSeason(SeasonId);
var firstHalfTablesProcessed = (from table in firstHalfTables
orderby table.FirstHalfPoints, table.GD, table.GF
select table).Reverse()
FirstHalfTableRepeater.DataSource = firstHalfTablesProcessed;
Or you could make your comparison delegate return the proper sorting (probably better as normal function than lambda):
int FirstHalfTableComparison(FirstHalfTable t1, FirstHalfTable t2)
{
int result = t1.FirstHalfPoints.CompareTo(t2.FirstHalfPoints);
if (result == 0)
{
result = t1.GD.CompareTo(t2.GD);
if (result == 0)
result = t1.GF.CompareTo(t2.GF);
}
return result;
}
You can use that like this:
firstHalfTables.Sort(FirstHalfTableComparison);
Upvotes: 2