首页 文章

LINQ Orderby降序查询

提问于
浏览
372

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

我有一个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个参数

从我所读到的,我很确定我做的第一种方式应该有效 . 我已经尝试将降序改为升序只是为了看它是否做了什么,但它保持不变 .

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

4 回答

  • 580

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

    喜欢:

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

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

  • 147

    我认为这首先失败了,因为你订的是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;
    
  • 0

    我认为第二个应该是

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

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

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

    这种方法很好,但如果你想直接进入List对象:

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

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

    需要注意的是,我无法回想起Where()调用中是否接受!(not)表达式 .

相关问题