lundi 31 octobre 2016

Call ToString() on a dynamically build expression

I'm trying to build an dynamic expression from a string of property-names (given by the user) on an IQueryable named source. This is what I have so far:

var parameter = Expression.Parameter(source.ElementType, "x");
var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var selector = Expression.Lambda(member, parameter);

which will give me something like x => x.MainProperty.SubProperty when the input would be MainProperty.SubProperty.

I now need to add ToString() to the expression selector so it will produce the expression x => x.MainProperty.SubProperty.ToString() which then can be passed into other methods.

How can this be done?

Edit 1

I'm trying to build a dynamic GroupBy where the type of the key doesn't matter. But the property to group by can be of type Guid, int or something else. That's why I need to call ToString().

public static IEnumerable<IGrouping<T, string>>(IQueryable<T> source, string propertyChain)
{
    var parameter = Expression.Parameter(source.ElementType, "x");
    var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
    var selector = Expression.Lambda(member, parameter);

    // currently here I have x => x.MainProperty.SubProperty
    // here I would Invoke the GroupBy of IQueryable with T and string via reflection
}





Aucun commentaire:

Enregistrer un commentaire