【问题标题】:LINQ Orderby Descending QueryLINQ Orderby 降序查询
【发布时间】:2011-07-17 17:15:13
【问题描述】:

我相信这将是一个相对简单的。

我有一个 LINQ 查询,我想按最近创​​建的日期排序。

见:

        var itemList = from t in ctn.Items
                        where !t.Items && t.DeliverySelection
                        orderby t.Delivery.SubmissionDate descending
                        select t;

我也试过了:

       var itemList = (from t in ctn.Items
                        where !t.Items && t.DeliverySelection
                        select t).OrderByDescending();

但这给出了一个错误:

方法没有重载 'OrderByDescending' 需要 0 个参数

根据我的阅读,我相当确定我的第一种方法应该可行。我尝试将降序更改为升序,只是为了看看它是否有任何作用,但它保持不变。

如果有人可以查看查询并查看我是否做错了什么,我将不胜感激。谢谢:)

【问题讨论】:

    标签: c# linq sql-order-by


    【解决方案1】:

    您需要选择一个要排序的属性并将其作为 lambda 表达式传递给OrderByDescending

    喜欢:

    .OrderByDescending(x => x.Delivery.SubmissionDate);
    

    真的,虽然您的 LINQ 语句的第一个版本应该可以工作。 t.Delivery.SubmissionDate 是否实际填充了有效日期?

    【讨论】:

    • 您好 optus,感谢您的回复。我已经弄清楚问题出在哪里了。我正在使用一个分页列表,它实际上是从那个助手类中进行排序的。一旦时间限制结束,我会将您的答案标记为正确:)
    【解决方案2】:

    我认为这首先失败了,因为您正在订购 null 值。如果 Delivery 是一个外键关联表,那么您应该首先包含此表,示例如下:

    var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                        where !t.Items && t.DeliverySelection
                        orderby t.Delivery.SubmissionDate descending
                        select t;
    

    【讨论】:

    • include 相当于 DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith(i => i.Delivery); ctn.LoadOptions = dlo;
    【解决方案3】:

    我认为第二个应该是

    var itemList = (from t in ctn.Items
                    where !t.Items && t.DeliverySelection
                    select t).OrderByDescending(c => c.Delivery.SubmissionDate);
    

    【讨论】:

    • 我认为对他公平,我在发布时输入了错误的查询(即留在倒数第二行),他可能只是复制并粘贴以演示 lambda 的使用按降序排列。
    【解决方案4】:

    只是为了以我出于某种原因更喜欢使用的不同格式显示它: 第一种方式将您的 itemList 作为 System.Linq.IOrderedQueryable 返回

    using(var context = new ItemEntities())
    {
        var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                    .OrderByDescending(x => x.Delivery.SubmissionDate);
    }
    

    这种方法很好,但如果您想将其直接放入列表对象中:

    var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                    .OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
    

    您所要做的就是将 .ToList() 调用附加到 Query 的末尾。

    需要注意的是,我不记得在 Where() 调用中是否可以接受 !(not) 表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2020-04-20
      相关资源
      最近更新 更多