[C#] 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();

그러나 이것은 오류를 제공합니다 :

‘OrderByDescending’메소드에 과부하가 없으면 0 개의 인수를 사용합니다

내가 읽은 것에서, 내가 한 첫 번째 방법은 효과가 있다고 확신합니다. 나는 아무것도하지 않는지 확인하기 위해 내림차순으로 오름차순으로 변경하려고 시도했지만 그대로 유지됩니다.

누군가가 쿼리를보고 내가 잘못하고 있는지 확인할 수 있다면 감사 할 것입니다. 감사 🙂



답변

정렬 할 속성을 선택하고 람다 식으로 전달해야합니다. 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);
}

이 방법은 괜찮지 만 목록 객체로 직접 원한다면 :

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

Query 끝에 .ToList () 호출을 추가하기 만하면됩니다.

Where () 호출에서! (not)식이 허용되는지 기억할 수없는 점이 있습니다.


답변