I'm using this dynamic linq orderby function which I got from here.
This works fine with nested properties so I could do this:
var result = data.OrderBy("SomeProperty.NestedProperty");
The problem is that if SomeProperty is null then performing the OrderBy on the NestedProperty throws the infamous "Object reference not set to an instance of an object".
My guess is that I need to customize the following lines to handle the exception:
expr = Expression.Property(expr, pi);
// Or
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
I thought about creating a statement body where I could in the worst case scenario use a try catch but that didn't work as you can't have statement bodies within orderby linq statements: "A lambda expression with a statement body cannot be converted to an expression tree"
I'm lost over here, any suggestions on how I can accomplish this?
By the way, this is for Linq to Objects, not database related.
How about generics:
Helper Method:
Sample Hierarchy:
Example:
Output: