KingKerosin KingKerosin - 1 month ago 6
C# Question

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<string, T>>(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
}

Answer

You can use the following Expression.Call overload for instance:

var toString = Expression.Call(member, "ToString", Type.EmptyTypes);
var selector = Expression.Lambda<Func<T, string>>(toString, parameter);
return source.GroupBy(selector);