mercredi 22 août 2018

Iterate through property and creating an Expression

Im not used to working with expression funcs, but my problem is: I get the name of a property as a string, i then need to convert this to the appropriate expression.

Currently im doing something like this:

if (string.Equals(propertyString, "customerNo", StringComparison.InvariantCultureIgnoreCase))
        {
            return _repo.DoSomething(x=>x.CustomerNo);
        }
if (string.Equals(propertyString, "customerName", StringComparison.InvariantCultureIgnoreCase))
        {
            return _repo.DoSomething(x => x.CustomerName);
        }

With the repo function something like this:

public IEnumerable<ICustomer> DoSomething(Expression<Func<IObjectWithProperties, object>> express)
{
    //Do stuff
}

What i would like to do, is use reflection like this:

var type = typeof(IObjectWithProperties);
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    if(string.Equals(property.Name,propertyString,StringComparison.InvariantCultureIgnoreCase))
        return _repo.DoSomething(x => x.PROPERTY);
}

But I can't figure out a way to generate the expression func from the propertyinfo





Aucun commentaire:

Enregistrer un commentaire