user1893874
user1893874

Reputation: 843

Order by with condition

I want to get the records with "Restricted" at top. here Is my query:

var records = (from entry in db.Table1
                    orderby entry.Always_Prohibited                              
                    select new
                           {
                                 RowID = entry.RowID,
                                 VehicleMake = entry.Make,
                                 VehicleModel = entry.Model,
                                 Restricted = (entry.Always_Prohibited == null || entry.Always_Prohibited == "False") ? "Restricted" : "Not Restricted"
                           }).ToList();

I tried by Orderby but it is not working because entry.Always_Probibited is a string field. Please suggest me.

Upvotes: 1

Views: 76

Answers (2)

Alisworld
Alisworld

Reputation: 1

User then below give code. It will help to you.

var records = (from entry in db.Table1.AsQueryable();
                orderby entry.Always_Prohibited                              
                select new
                       {
                             RowID = entry.RowID,
                             VehicleMake = entry.Make,
                             VehicleModel = entry.Model,
                             Restricted = (entry.Always_Prohibited == null || entry.Always_Prohibited == "False") ? "Restricted" : "Not Restricted"
                       }).ToList();

Upvotes: 0

Blindy
Blindy

Reputation: 67477

If you have only two values, simply order descending:

from entry in db.Table1
orderby entry.Always_Prohibited descending

If you have more, assign integer values to your strings:

from entry in db.Table1
orderby entry.Always_Prohibited=="A" ? 0 : entry.Always_Prohibited=="B" ? 1 : 2 // and so on

As a side note, strings are a pretty terrible way of storing state in databases. You should redesign it to store it as well defined integers (preferably as foreign keys in master lookup tables, ie strongly typed enums).

Upvotes: 1

Related Questions