按条件订购

本文关键字:条件 | 更新日期: 2023-09-27 18:24:05

我想获得顶部带有"Restricted"的记录。这是我的问题:

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

我尝试了Orderby,但由于进入,它不起作用。Always_Probhibited是一个字符串字段。请推荐我。

按条件订购

如果只有两个值,只需按降序排列:

from entry in db.Table1
orderby entry.Always_Prohibited descending

如果您有更多,请为字符串分配整数值:

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

顺便说一下,字符串是在数据库中存储状态的一种非常糟糕的方式。您应该重新设计它,将其存储为定义良好的整数(最好是作为主查找表中的外键,即强类型枚举)。

用户在下面给出代码。这将对你有所帮助。

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