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.
expr = Expression.Property(expr, pi);
setsexpr
to null and further code does not handle it. The easiest way to fix it isexpr = Expression.Property(expr, pi) ?? default(T);
. However you'll need to check if you ok with applied order in this case. – Satoexpr
is whole expression, we can't do it. So now easier way is yoursOrderByLambda()
; Func generic args isMyType, string
, I think it's enough to returnString.Empty
incatch
– SatoExpression.TryCatch
, but I'm really unfamiliar with expressions techinque. However, I've got alternative solution, based on simple reflection traversing. Check answer with example. – Sato