Ordering data by boolean

I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefault

At first, the code was

var listOfData = Db
.TableName
.Where(u => u.UserId == userId)
.OrderBy(u => u.IsDefault)
.ToList();


Which when writing down, sounds correct. However is wrong as this will order by 0 > 1, and True = 1.

So I changed the statement to;

var listOfData = Db
.TableName
.Where(u => u.UserId == userId)
.OrderBy(u => u.IsDefault ? 0 : 1)
.ToList();


However, I could have also written this 2 other ways.

.OrderBy(u => !u.IsDefault)


OR

.OrderByDescending(u => u.IsDefault)


Now in my mind, u.IsDefault ? 0 : 1 reads better, and the other two could be misread as the not wanting the default value first.

What is your view on this?

I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view.

Let the client, its view, its display control, or whatever sort the items according to its needs.

• Good point actually. Could just do the ordering when building up the view model. – Tim B James Jan 12 '17 at 13:46
• I am going with this answer, as it is the simpler solution for my needs. Thanks for your help. – Tim B James Jan 13 '17 at 10:59

I would go with .OrderBy(u => !u.IsDefault) the other 2 don't quite fit in my opinion.

You have 2 alternative options

1. Declare a property that is called IsNotDefault and use it there .OrderBy(u => u.IsNotDefault) it will return !IsDefault so it flips the results.

2. The best option would be to use enum :

public enum MyEnum
{
Default,
NonDefault,
}


Note think of a better name for that enum..

Now you can use it just like your ternary operator but without the ternary operator :

public MyEnum IsDefault {...}
.OrderBy(u => u.IsDefault)


You can even apply more values and it will still order them in the right way.

• Yeah actually considered using Enums, will take a look. – Tim B James Jan 12 '17 at 13:46
• Why the down-vote ? – Denis Jan 12 '17 at 15:28
• Not me, you still got a +1 from me. – Tim B James Jan 12 '17 at 15:31
• I'm just wondering if there is anything incorrect in the answer :P – Denis Jan 12 '17 at 15:58
• As much as this is a great option. For now my needs are purely for boolean, and it would require too much of a code update for introducing the Enum. Thanks for your help. – Tim B James Jan 13 '17 at 10:59