2

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

nikoshr
  • 32,926
  • 33
  • 91
  • 105
YannickIngenierie
  • 602
  • 1
  • 13
  • 37

1 Answers1

2

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
)
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64