根据Linq的条件更改订单

时间:2012-01-20 14:37:15

标签: c# asp.net linq sql-order-by

  

可能重复:
  Conditional “orderby” sort order in LINQ

请告诉我如何使用不同的列对以下查询进行排序,具体取决于条件,例如现在它按OfferID降序排序,

var myoffer = (from b in MMEntities.OfferDisplays.AsExpandable().Where(pred)
                       where b.Offers.Accounts.AccountID == accountID && b.Offers.OfferID != 0  && !((from bb in MMEntities.OfferDisplays.AsExpandable().Where(pred)
                             where
                               bb.Offers.Accounts.AccountID == accountID && bb.Offers.OfferID != 0  orderby
                             bb.Offers.OfferID descending
                             select new
                             {
                                 bb.Offers.OfferID
                             }).Take(10)).Contains(new { b.Offers.OfferID }) &&
                         b.Offers.Accounts.AccountID == accountID orderby
                         b.Offers.OfferID descending

2 个答案:

答案 0 :(得分:0)

你可以用吗? :`OrderBy'语句中的:运算符

如果条件为真,则

condition ? value1 : value2评估为value 1,如果条件为假,则value 2评估为{{1}}。

答案 1 :(得分:0)

编辑如果您将使用相同的排序参数两次:

您可以尝试使用Let创建本地参数:

var myofferUnsorted = (from b in MMEntities.OfferDisplays.AsExpandable().Where(pred)
                    **let OrderArg = b.Offers.OfferID**
                   where b.Offers.Accounts.AccountID == accountID && b.Offers.OfferID != 0  && !((from bb in MMEntities.OfferDisplays.AsExpandable().Where(pred)
                         where
                           bb.Offers.Accounts.AccountID == accountID && bb.Offers.OfferID != 0                                  orderby
                         OrderArg descending
                         select new
                         {
                             bb.Offers.OfferID
                         }).Take(10)).Contains(new { b.Offers.OfferID }) &&
                     b.Offers.Accounts.AccountID == accountID 
orderby
                         OrderArg  descending

在这种情况下,您必须将条件嵌入到linq中: let OrderArg = flag ? b.Offers.OfferID : b.Offers.SmthElse