mardi 3 février 2015

Dynamically Sort Datetime with reflexion and expression lambda

I built a code to sort several type like string,number ... Now I try to Had date.



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 Typ = pinfo.PropertyType.Name
Dim toStr As Expression

Dim Expr As Expression = Expression.Property(paramExpr, pinfo)

toStr = Expression.Call(If(pinfo.PropertyType.IsValueType, Expr, Expression.Coalesce(Expr, Expression.Constant(String.Empty))), "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


The problem is when I sort it's not sort Date but a string like



31/12/2005; 31/11/2011; 31/10/2007 ...



When I Sort it's better to find



31/11/2011; 31/10/2007; 31/12/2005



Then I try this modify



If Typ.Contains("DateTime") Then 'Add For DateTime here
toStr = Expression.Call(If(pinfo.PropertyType.IsValueType, Expr, Expression.Coalesce(Expr, Expression.Constant(Date.MinValue))), "ToString", Nothing)
Else
toStr = Expression.Call(If(pinfo.PropertyType.IsValueType, Expr, Expression.Coalesce(Expr, Expression.Constant(String.Empty))), "ToString", Nothing)
End If


but i don't know how replace 'ToString' Or perhaps there is a better way


Thnks for your help






Aucun commentaire:

Enregistrer un commentaire