c# - Dynamic linq order by on nested property with null properties -


i'm using dynamic linq orderby function got here.

this works fine nested properties this:

var result = data.orderby("someproperty.nestedproperty"); 

the problem if someproperty null performing orderby on nestedproperty throws infamous "object reference not set instance of object".

my guess need customize following lines handle exception:

expr = expression.property(expr, pi);  // or  lambdaexpression lambda = expression.lambda(delegatetype, expr, arg);     

i thought creating statement body in worst case scenario use try catch didn't work can't have statement bodies within orderby linq statements: "a lambda expression statement body cannot converted expression tree"

i'm lost on here, suggestions on how can accomplish this?

by way, linq objects, not database related.

static void main(string[] args) {     var data = new list<mytype>() {         new mytype() { someproperty = new inner() { nestedproperty = "2" }},         new mytype() { someproperty = new inner() { nestedproperty = "1" }},         new mytype() { someproperty = new inner() { nestedproperty = "3" }},         new mytype(),     }.asqueryable();     var sorted = data.orderby(x => getpropertyvalue(x, "someproperty.nestedproperty"));      foreach (var mytype in sorted)     {        try        {           console.writeline(mytype.someproperty.nestedproperty);        }        catch (exception e)        {           console.writeline("null");        }     } }  public static object getpropertyvalue(object obj, string propertyname) {     try     {         foreach (var prop in propertyname.split('.').select(s => obj.gettype().getproperty(s)))         {             obj = prop.getvalue(obj, null);         }         return obj;     }     catch (nullreferenceexception)     {         return null;     } } 

Comments