Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by sort order that is greater than 0

Tags:

linq

c#-3.0

I am trying to sort a bunch of objects that have sort order, however some fields have been initialized to 0, so I want to first display all users/objects that have a sort order (in the actual correct order) then display then others e.g.

my list

{id:4,name:"Tom", sortoder:0}
{id:14,name:"Bee", sortoder:0}
{id:401,name:"Mike", sortoder:1}
{id:13582,name:"Monty", sortoder:2}
{id:55,name:"Charlie", sortoder:0}
{id:9,name:"Khan", sortoder:9}

        var fields = GetFields(myobject) //get fields (not really relevant)
                     .OrderBy(x => x.sortoder > 0) //this is where I am stuck on
                     .ToList();

My lists are all dislaying users with 0 at the top then those that have a sort order

like image 966
Haroon Avatar asked Dec 16 '22 04:12

Haroon


1 Answers

Either use ThenBy to apply a second ordering after the first:

var fields = GetFields(myobject)
    .OrderByDescending(x => x.SortOrder > 0)
    .ThenBy(x => x.SortOrder)
    .ToList();

Or you could use a conditional expression to replace the value 0 with int.MaxValue (assuming that int.MaxValue does not occur as a legitimate SortOrder):

var fields = GetFields(myobject)
    .OrderBy(x => x.SortOrder == 0 ? int.MaxValue : x.SortOrder)
    .ToList();
like image 116
Mark Byers Avatar answered Apr 16 '23 23:04

Mark Byers