嵌套属性为null时,动态linq排序 [英] Dynamic linq order by on nested property with null properties

查看:57
本文介绍了嵌套属性为null时,动态linq排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从此处获得的动态linq orderby函数.

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");

问题在于,如果SomeProperty为null,则对NestedProperty执行OrderBy会引发臭名昭著的对象引用未设置为对象实例".

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

我曾考虑过创建一个语句主体,在最坏的情况下我可以使用try catch,但是由于在orderby linq语句中不能包含语句主体,因此无法正常工作:带有语句主体的lambda表达式不能转换为表达式树"

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?

顺便说一句,这是针对Linq to Objects的,与数据库无关.

推荐答案

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

这篇关于嵌套属性为null时,动态linq排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆