jeudi 17 octobre 2019

Can I remove the need for the double lambda in this generic expression?

I've made this extension method (I know right now there's no exception checking etc, will be added once I'm sure the function is actually correct):

public static IEnumerable<TSource> ChangeProperty<TSource, TResult>(this IEnumerable<TSource> source,Expression<Func<TSource,TResult>> res, Func<TSource, TResult> changeProp)
    {
        Type type = typeof(TSource);
        MemberExpression member = res.Body as MemberExpression;
        var name = member.Member.Name;

        foreach (var x in source)
        {
            var prop = type.GetProperty(name);
            prop.SetValue(x, changeProp(x));
            Console.WriteLine(prop.GetValue(x));
        }
        return source;
    }

And is used in this context(Remove unwanted tags strips html tags out of a string):

_dc.EmailTemplates
.ChangeProperty(x=>x.Body,z=>RemoveUnwantedTags(z.Body))
.ToList();

But I don't like that I have to use a double lambda, one for getting the property name, and then one for executing the function. I don't know if it's my lack of understanding on how Expression<> works, or if im missing something really obvious but would really appreciate the help!





Aucun commentaire:

Enregistrer un commentaire