lincx
lincx

Reputation: 409

Sort by second field if the first field is null

How to convert this in C# linq/lambda query

select *
from meetings
order by ISNULL(ActualStartDate, StartDate) desc

so far I tried this but seems like it doesn't work:

meetings.OrderByDescending(m => m.ActualStartDate ?? m.StartDate);

UPDATE:

Actually this is correct. The problem is on the listview that shows the item. Apologies.

Actually my real problem is when both ActualStartDate and StartDate is null and I want it to show last. But thats a separate question I guess.

Upvotes: 1

Views: 717

Answers (3)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

Others answers are correct, but you can use this way also.

 var meetings = meetings.OrderByDescending(p => p.ActualStartDate.HasValue)
                .ThenBy(p => p.StartDate)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500645

I suspect you want:

var sorted =  meetings.OrderByDescending(m => m.ActualStartDate ?? m.StartDate);

Note that calling the method won't change meetings - you need to use the return value which will be a sorted sequence of results. (This is in line with how LINQ works in general.)

If that still doesn't work, and assuming this is LINQ to SQL or something similar, you should look at the generated SQL to work out what's going on... then you can try to adjust your query appropriately.

Upvotes: 3

TamerM
TamerM

Reputation: 762

You are missing the "m." for the StartDate:

meetings.OrderByDescending(m => m.ActualStartDate ?? m.StartDate);

Upvotes: 1

Related Questions