Search code examples
c#sqllambdapaginationsql-order-by

Order by mapped string instead of integer


In the Database table "Device" have a column "Status" (integer)

Name Status
Device1 1
Device2 2
Device3 3
Device4 4
Device5 3

In my Application I have map the column "Status" to human readable words (string)

public enum Status
{
   Start = 1,
   Stop = 2,
   Running = 3,
   new Device = 4,
}

If I order by "status" the result will be order by integer.

_repository.Query<Device>().OrderBy(c=>c.status)
                           .Skip(skip)
                           .Take(500);

In the table "Devices" I have more than 60.000 records, so I use paging

Result:

Name Status
Device1 Start
Device2 Stop
Device3 Running
Device5 Running
Device4 new Device

What I need:

Name Status
Device4 new Device
Device3 Running
Device5 Running
Device1 Start
Device2 Stop

What can I do?


Solution

  • You could use the conditional operator:

    var query = _repository.Query()
        .OrderBy(c => c.Status == Status.NewDevice ? 0 : c.Status == Status.Running ? 1 : c.Status == Status.Start ? 2 : 3)
        .Skip(skip)
        .Take(500);