Haroon
Haroon

Reputation: 3472

Order by sort order that is greater than 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

Upvotes: 4

Views: 2502

Answers (3)

vc 74
vc 74

Reputation: 38179

You could implement an IComparer or use a quick and dirty way like the following:

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

How about:

.OrderBy(x => x.sortorder != 0 ? x.sortoder : int.MaxValue)

This basically means "treat 0 as a special value, equivalent to int.MaxValue - but otherwise just use the existing sortorder".

Mark's approach of first ordering by "have a sort order vs don't have a sort order" and then by the sort order value (which will obviously be 0 for the second group) would work fine too - it's really just a matter of personal preference which approach you use.

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 838156

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();

Upvotes: 8

Related Questions