0

I am trying to do a OrderByDescending on my LINQ query. Currently I am doing OrderByDescending on ProcedureDate field.

Business Scenario: A user can come in the application and add ChangeProcedureDates in application upto 3 times. So in database there are additional fields called ChangeProcedureDate1, ChangeProcedureDate2 and ChangeProcedureDate3.

What I am trying to accomplish: I want to modify my LINQ query so it can check to see if in cases where ChangeProcedureDate1, ChangeProcedureDate2 and ChangeProcedureDate3 are NULL then OrderBy ProedureDate since there were no changes. If ProcedureDate, ChangeProcedureDate1 is filled and ChangeProcedureDate2 and ChangeProcedureDate3 are NULL then we need to OrderBy ChangeProcedureDate1. And same for ChangeProcedureDate2 and ChangeProcedureDate3. Basically I need to find the latest date entry among multiple DateTimeFields and do orderby on that.

Below is my LINQ query.

 var unsortedItems = context.ReservationRequests
                   .Where(s => ((s.ReservationRequestStatusId.HasValue) &&
                   (s.ReservationRequestStatusId.Value == ReservationRequestStatusId)) &&
                   (Roles.Any(y => s.SubmitterGroupName == y) ||
                   s.CreatedBy == currentUserGuid))
                 .OrderByDescending(x => x.ProcedureDate  ?? DateTime.MinValue);

I am having hard time trying to understand how can I do this in LINQ?

HereToLearn_
  • 986
  • 4
  • 19
  • 39
  • can't you use ThenByDescending as mention in this stackoverflow question https://stackoverflow.com/questions/298725/multiple-order-by-in-linq – PNP Mar 16 '18 at 02:16

1 Answers1

1

Try this:

.OrderByDescending(x => x.ChangeProcedureDate3 ?? x.ChangeProcedureDate2 ?? x.ChangeProcedureDate1 ?? x.ProcedureDate);

Or, change orders of properties as you need.

Backs
  • 22,763
  • 4
  • 44
  • 72
  • Isin't that saying (check to see if ProcedureDate is not null. If so move to ChangeProcedureDate1 . If ChangeProcedureDate1 is null then move to ChangeProcedureDate2. If ChangeProcedureDate2 is null then move to ChangeProcedureDate3 )? – HereToLearn_ Mar 16 '18 at 02:04
  • If thats the case then this would fail because a user can enter in ChangeProcedureDate2 . Which does not mean that we are nulling ChangeProcedureDate1 and ProcedureDate – HereToLearn_ Mar 16 '18 at 02:06
  • 1
    @HereToLearn_ than reorder from `ChangeProcedureDate3` to `ChangeProcedureDate1` then. You will get latest date – Backs Mar 16 '18 at 02:08
  • @HereToLearn_ how it's going? – Backs Mar 16 '18 at 10:49
  • This worked fine for me. Thanks a lot for your idea..I cant believe i couldnt see it myself – HereToLearn_ Mar 16 '18 at 19:41