HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Ordering data by boolean

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dataorderingboolean

Problem

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?

Solution

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.

Context

StackExchange Code Review Q#152434, answer score: 9

Revisions (0)

No revisions yet.