lundi 29 octobre 2018

How to create lambda expressions for every property of a class

I have a following problem. I have to iterate over all the properties of the class to configure some builder. A class has a lot of properties, so the code is cumbersome. It looks like this:

var b = builder<MyTypeWith1000Properties>
    .WithProperty(x=>x.Property1)
    .WithProperty(x=>x.Property2)
    ...
    .WithProperty(x=>x.Property1000);

The code is repeated in many places for many differend types, not only MyTypeWith1000Properties. I was thinking about creating some extension, like this:

var b = builder<MyTypeWith1000Properties>
    .WithAllProperties();

and then in the WithAllProperties I could iterate over type properties using Reflection, like this:

public static IDataExtractor<T> WithAllProperties(this IDataExtractor<T> extractor)
{
    var properties = typeof(T).GetProperties();
    foreach (var property in properties)
    {
        extractor = extractor.WithProperty(/*the problem is here/*);
    }
    return extractor;
}

How to convert the property variable in the loop to a corresponding expression

Expression<Func<TRow, TValue>> propertyExpression

as this is what WithProperty expects





Aucun commentaire:

Enregistrer un commentaire