vb.net - 用于对具有空值的字段进行排序的表达式 Lambda

标签 vb.net linq dynamic

我使用动态方法来排序对象列表。

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 是我要过滤的字段的名称。

当我没有空值时,它是完美的,但是当我有空值时,我在行 query = sortFunc(query).ToList() 中收到异常:

Object reference not set to an instance of an object

我看到 Expression.CallISNullOrEmpty 的代码不同,但我不知道在我的情况下如何正确使用它。我希望 null 或 Empty 像“”一样首先出现。

感谢您的帮助和解释

最佳答案

您可以更改 toStr 表达式以包含 Coalesce正确表达式是常量的运算。请注意,左侧表达式需要是引用类型(或可为 null 的值类型),因此您还需要确保属性类型不是值类型。

这是一个应该有效的示例:

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

关于vb.net - 用于对具有空值的字段进行排序的表达式 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27720165/

相关文章:

asp.net - 下载带有 "save as"的文件

asp.net - 将复杂对象作为参数发送给 Asp.Net PageMethod

时间:2019-03-08 标签:c#linqwhereconditionalif

Python 动态帮助和自动完成生成

.net - 匿名类型缺少成员问题的动态 View - MVC3

c# - 在 asp.net 中使用 croppic

asp.net - 将子字符串转换为链接的正则表达式

c# - Linq:使用不同的 IEnumerable<bool> 过滤列表

c# - 使用 StartsWith、EndsWith 和 Contains 创建 Linq 表达式并传递 Expression<Func<T, string>>

运行时的 WPF Binding.ValidationRules