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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With