簡體   English   中英

LINQ Orderby降序查詢

[英]LINQ Orderby Descending Query

我相信這將是一個相對簡單的。

我有一個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參數

從我所讀到的,我很確定我做的第一種方式應該有效。 我已經嘗試將降序改為升序只是為了看它是否做了什么,但它保持不變。

如果有人能夠查看查詢並查看我是否做錯了什么,我將不勝感激。 謝謝 :)

您需要選擇要排序的屬性並將其作為lambda表達式傳遞給OrderByDescending

喜歡:

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

真的,雖然你的LINQ語句的第一個版本應該工作。 t.Delivery.SubmissionDate實際上是否填充了有效日期?

我認為這首先失敗了,因為你訂的是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;

我認為第二個應該是

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

只是為了以某種原因顯示我喜歡使用的不同格式:第一種方式將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)表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM