Programing

linq에서 2 개의 필드로 orderby를 사용하는 방법은 무엇입니까?

lottogame 2020. 7. 7. 07:42
반응형

linq에서 2 개의 필드로 orderby를 사용하는 방법은 무엇입니까? [복제]


이 질문에는 이미 답변이 있습니다.

데이터베이스 테이블에 이러한 값이 있다고 가정 해보십시오.

id = 1
StartDate = 1/3/2010
EndDate =  1/3/2010

id = 2
StartDate = 1/3/2010
EndDate = 1/9/2010

이제 나는 지금까지 내 linq에 대한이 orderby를 가지고있다.

var hold = MyList.OrderBy(x => x.StartDate).ToList();

그러나 종료 날짜도 사용하여 주문하고 싶습니다.

그래서 내가 원하는 순서대로

id 2
id 1

그래서 endDates더 큰 우선입니다. 비교 기능이나 무언가를 사용하기 위해 이것을 변경 해야하는지 확실하지 않습니다.


MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

사용 ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

쿼리 구문을 사용하여 다음과 같이 말할 수도 있습니다.

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescendingIOrderedEnumerable의해 반환되는 확장 방법입니다 OrderBy. 관련 방법도 참조하십시오 ThenBy.


MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

OrderBy에서 내림차순 키워드도 사용할 수 있습니다 (필요한 경우). 가능한 또 다른 대답은 다음과 같습니다.

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)

또는

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending

주문할 필드가 두 개 이상인 경우 다음을 시도하십시오.

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

"ThenBy"클래 솔로 다른 필드를 추가 할 수 있습니다

참고 URL : https://stackoverflow.com/questions/1989674/how-to-use-orderby-with-2-fields-in-linq

반응형