Expression Lambda to order fields with null value

♀尐吖头ヾ 提交于 2020-01-21 14:34:45

问题


I use a dynamic method to order a list of object.

For Each Sort In MesDonnees.MesOptions
    If Sort.Sens < 2 Then
        Dim sortPropertyName As String = Sort.ColName

        If (TypeClass.GetProperties().Any(Function(prop) prop.Name = sortPropertyName AndAlso prop.CanRead)) Then

            'Information sur la propriété recherchée
            Dim pinfo As PropertyInfo = TypeClass.GetProperty(sortPropertyName)

            Dim Expr As Expression = Expression.Property(paramExpr, pinfo)
            Dim Tostr As Expression = Expression.Call(Expr, "ToString", Nothing)

            Dim orderByFunc As Func(Of MaClass, Object) = Expression.Lambda(Of Func(Of MaClass, Object))(Tostr, paramExpr).Compile()
            Dim sortFunc As Func(Of IEnumerable(Of MaClass), IOrderedEnumerable(Of MaClass)) = Nothing

            If (Not CBool(Sort.Sens)) Then
                sortFunc = (Function(source) source.OrderBy(orderByFunc))
            Else
                sortFunc = (Function(source) source.OrderByDescending(orderByFunc))
            End If

            query = sortFunc(query).ToList()

        End If
    End If
Next

Sort.ColName is the name of my field I want to filter.

When I have no null value, it's perfect but when I have a null value, I get an exception in the line query = sortFunc(query).ToList() :

Object reference not set to an instance of an object

I see different code with Expression.Call and ISNullOrEmpty but I don't know how use it correctly in my case. I want null or Empty are in first like a "".

Thanks for your help and explanation


回答1:


You can change your toStr expression to include a Coalesce operation where the right expression is a constant. Note that the left expression needs to be reference type (or a nullable value type) so you also need to ensure that the property type is not a value type.

Here's an example that should work:

Dim toStr As Expression = Expression.Call(
    If(pinfo.PropertyType.IsValueType, expr, Expression.Coalesce(expr, Expression.Constant(String.Empty))),
    "ToString",
    Nothing
)


来源:https://stackoverflow.com/questions/27720165/expression-lambda-to-order-fields-with-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!