ChatGPT解决这个技术问题 Extra ChatGPT

LINQ Orderby 降序查询

我有一个 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();

但这给出了一个错误:

No overload for method 'OrderByDescending' takes 0 arguments

根据我的阅读,它应该工作的第一种方式。我尝试将 descending 更改为 ascending 只是为了看看它是否有任何作用,但它保持不变。

我究竟做错了什么?


B
Bakudan

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

喜欢:

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

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


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

我认为这首先失败了,因为您正在订购 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;
a
abatishchev

我认为第二个应该是

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

我认为对他公平,我在发布时输入了错误的查询(即留在倒数第二行),他可能只是复制并粘贴以演示 lambda OrderByDescending 的使用。
B
Bernard Vander Beken

只是出于某种原因以我更喜欢使用的不同格式显示它:第一种方法将您的 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() 调用附加到查询的末尾。

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