对具有null属性的嵌套属性执行动态linq排序

本文关键字:属性 执行 动态 linq 排序 嵌套 null | 更新日期: 2023-09-27 18:22:15

我使用的是从这里得到的动态linq orderby函数。

这对嵌套属性很好,所以我可以这样做:

var result = data.OrderBy("SomeProperty.NestedProperty");

问题是,如果SomeProperty为null,那么对NestedProperty执行OrderBy会抛出臭名昭著的"对象引用未设置为对象实例"。

我的猜测是,我需要自定义以下行来处理异常:

expr = Expression.Property(expr, pi);
// Or
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);    

我曾想过创建一个语句体,在最坏的情况下,我可以使用try-catch,但这没有奏效,因为在orderby linq语句中不能有语句体:"带语句体的lambda表达式不能转换为表达式树"

我在这里迷路了,有什么建议可以帮我完成吗?

顺便说一句,这是针对Linq到对象的,与数据库无关

对具有null属性的嵌套属性执行动态linq排序

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;
    }
}

泛型如何:

辅助方法:

public static Expression<Func<TEntity, TResult>> GetExpression<TEntity, TResult>(string prop)
        {
            var param = Expression.Parameter(typeof(TEntity), "p");
            var parts = prop.Split('.');
            Expression parent = parts.Aggregate<string, Expression>(param, Expression.Property);
            Expression conversion = Expression.Convert(parent, typeof (object));
            var tryExpression = Expression.TryCatch(Expression.Block(typeof(object), conversion),
                                                    Expression.Catch(typeof(object), Expression.Constant(null))); 
            return Expression.Lambda<Func<TEntity, TResult>>(tryExpression, param);
        }

样本层次结构:

public class A
    {
        public A(B b)
        {
            B = b;
        }
        public B B { get; set; }
    }
    public class B
    {
        public B(C c)
        {
            C = c;
        }
        public C C { get; set; }
    }
    public class C
    {
        public C(int id)
        {
            this.Id = id;
        }
        public int Id { get; set; }
    }

示例:

var list = new List<B>
            { 
                new B(new A(new C(1))),
                new B(new A(new C(2))),
                new B(new A(new C(3))),
                new B(new A(null)),
                new B(null)
            }.AsQueryable();
var ordered = list.OrderByDescending(GetExpression<B, Object>("AProp.CProp.Id"));

输出:

3
2
1
Null
Null