Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list in .Net by one field, then another

Tags:

c#

sorting

linq

I have list of objects I need to sort based on some of their properties. This works fine to sort it by one field:

reportDataRows.Sort((x, y) => x["Comment1"].CompareTo(y["Comment1"]));
foreach (var row in reportDataRows) {
   ...
}

I see lots of examples on here that do this with only one field. But how do I sort by one field, then another? Or how about a list of many fields? It seems like using LINQ orderby thenby would be best, but I don't know enough about it to know how use it.

For the parameters, something like this that supports any number of fields to sort by would be nice:

var sortBy = new List<string>(){"Comment1","Time"};

I don't want to be writing code to do this in every one of my apps. I plan on moving this sort code to the class that holds the data so that it can do more advanced things like using a list of parameters and implicitly recognizing that the field is a date and sorting it as a date instead of a string. The reportDataRow object contains fields with this information, so I don't have to do any messy checks to find out if the field is supposed to be a date.

like image 593
Chris Avatar asked Oct 17 '25 01:10

Chris


2 Answers

Yes, I think it makes more sense to use OrderBy and ThenBy:

foreach (var row in reportDataRows.OrderBy(x => x["Comment1"]).ThenBy(x => x["Comment2"]) 
{
    ...
}

This assumes the other thing you want to order by is "Comment2".

like image 113
Kirk Woll Avatar answered Oct 19 '25 15:10

Kirk Woll


Try this:

reportDataRows.Sort((x, y) =>
{
    var compare = x["Comment1"].CompareTo(y["Comment1"]);
    if(compare != 0)
        return compare;

    return x["Comment2"].CompareTo(y["Comment2"]);
});
like image 30
Phil Avatar answered Oct 19 '25 14:10

Phil