Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

You can use the solution you already have. Just union the filtered data with the inverse of the filtered data.

You have to decide where the recordes with null As and B go. Then you can get the filtered data and Union it with the filtered out results (you can get that by querying where a == null || a.B == null)

If you want the the nulls to go before, do nullList.Union(nonNulls)

That way you have ordered nulls then ordered non-nulls in that order

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top