Mike
Mike

Reputation: 1580

dynamic linq query - OrderBy with properties that are null

I'm using The Ordering-By-String extensions from here: http://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/

In my datasource, some objects may be null, and therefore won't have a property of EHR (see screenshot).

How can I capture this case? I still want the nulls to be included in the ordered list, but just at the bottom or top.

Any suggestions?

EDIT: Some more clarification..

So my KendoUI grid is sending back a request to the server to order by a particular column. The column selected to orderby is "Month10.EHR". Month10 is a SubObject and EHR is the property. Some SubObjects don't exist and therefore don't have a property, and the subobject will be null. When performing the ordering, it notices that Month10 doesn't exist for one record, and therefore can't include it in the orderby.

I hope this makes sense.

Mike

Error

Upvotes: 1

Views: 1689

Answers (2)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

Test for null in the OrderBy Function.

IEnumerable<SomeType> myList;
// ...
var orderedList = myList.OrderBy(obj =>
                    obj == null 
                    || obj.Month10 == null 
                  ? defaultValue : obj.Month10.EHR);

Upvotes: 1

Vincent McNabb
Vincent McNabb

Reputation: 34659

Use Where to remove the elements which have a null order key, then use Concat to add them back again.

E.g.

IEnumerable List<Person> myList;
// ...
var orderedList = myList
    .Where(p => p.Age != null)
    .OrderBy(p => p.Age)
    .Concat(myList.Where(p => p.Age == null));

From reading your question again, it appears that you mean that the actual elements being sorted are null. What's the point of including them in the list at all in that case?

Upvotes: 2

Related Questions