I have LINQ Script where group by key possibly null. I got the result correctly and now I want to order by first null and then in descending order. because the group by key can be null so I cannot check as .hasValue!
In following approach I am getting null exception as it seems I am not handling null in order correctly?
var v25 = (from transaction in filteredTransactions
join schedule in schedules on
new { siteId = transaction.LoginSiteID, startDate = transaction.LoginDateTime.Date, payrollNumber = transaction.PayrollNumber } equals
new { siteId = schedule.SiteId, startDate = schedule.StartTime.Value.Date, payrollNumber = schedule.PayrollNumber }
into ezi_s_t
from scheduleTransactions in ezi_s_t.DefaultIfEmpty()
group transaction by scheduleTransactions into groupedScheduleTransactions
select new
{
Schedule = groupedScheduleTransactions.Key,
Transactions = groupedScheduleTransactions.ToList()
}
)
.OrderBy(x=> x.Schedule == null? null : x.Schedule.EziScheduleId)
.ToList();
You need to OrderByDescending() when it is null and then use ThenByDescending()
.OrderByDescending(x=> x.Schedule == null)
.ThenByDescending(x => x.Schedule?.EziScheduleId);
And about your comment, the reason you are getting System.NullReferenceException error is because if Schedule is null, you cannot access its properties (as there is none) so you need to change x.Schedule.EziScheduleId to x.Schedule?.EziScheduleId
Live Demo