Search code examples
c#linqlinq-to-sqldata-processing

OrderBy when a parent-value maybe null


Assume I want to order table q in T, by column q.As.OrderByDescending(p => p.Beginning).FirstOrDefault().B.C.

However, q.As.OrderByDescending(p => p.Beginning).FirstOrDefault() or a.B may be null, how can I achieve it?

My current code:

from q in T
let a = q.As.OrderByDescending(p => p.Beginning).FirstOrDefault()
where a != null
let b = a.B
where b!= null
orderby b.C
select q;

or

from q in T
let a = q.As.OrderByDescending(p => p.Beginning).FirstOrDefault()
where a != null && a.B != null
orderby a.B.C
select q;

However, that code only show the records that have all values in As and B. How can I achieve sorting without filtering any record?


Solution

  • This should work if you are using Linq-to-SQL

    from q in T
    orderby q.As.OrderByDescending(p => p.Beginning).FirstOrDefault().B.C
    select q;
    

    If this is actually Linq-to-Objects you will need to do this

    from q in T
    let x = q.As.OrderByDescending(p => p.Beginning).FirstOrDefault()
    orderby x == null ? null : x.B.C
    select q