I have a program that reads a json file with some property names of a certain class. The values of the configured property names should compose up a key.
Lets take an example:
Class:
class SomeClass
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public string PropertyThree { get; set; }
public string PropertyFour { get; set; }
}
var someClass = new SomeClass
{
PropertyOne = "Value1",
PropertyTwo = "Value2",
PropertyThree = "Value3",
PropertyFour = "Value4",
};
Configuration file:
{
"Properties": ["PropertyOne", "PropertyTwo"]
}
If I knew the properties at compile time I would have create a lambda like:
Func<SomeClass, string> keyFactory = x => $"{x.PropertyOne}|{x.PropertoTwo}"
Is there a way to compile such a lambda using expressions? Or any other suggestions maybe?
static Expression<Func<T, string>> CreateExpression<T>(string[] props) { var par = Expression.Parameter(typeof(T)); return Expression.Lambda<Func<T, string>>(Expression.Call(typeof(string).GetMethod("Join", new Type[] { typeof(string), typeof(object[]) }), Expression.Constant("|"), Expression.NewArrayInit(typeof(object), props.Select(prop => Expression.Property(par, prop)).ToArray())), par); }... not working in dotnetfidle since they blocking dynamic lambdas and only creates key as "Prop1|Prop2|Prop3|...|PropN"Func<SomeClass, string> keyFactory = x => string.Join("|", x.PropertyOne, x.PropertoTwo);