我可以删除这个通用表达式中对双 lambda 的需要吗?
Can I remove the need for the double lambda in this generic expression?
我做了这个扩展方法(我知道现在没有异常检查等,一旦我确定功能确实正确就会添加):
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;
}
并在此上下文中使用(从字符串中删除不需要的标签条 html 标签):
_dc.EmailTemplates
.ChangeProperty(x=>x.Body,z=>RemoveUnwantedTags(z.Body))
.ToList();
但我不喜欢我必须使用双重 lambda,一个用于获取 属性 名称,然后一个用于执行函数。我不知道是我对 Expression<> 的工作原理缺乏了解,还是我遗漏了一些非常明显的东西,但非常感谢您的帮助!
类似于 ForEach
在 List<T>
中的使用方式,所需的功能可以简化为
public static IEnumerable<TSource> Apply<TSource>(this IEnumerable<TSource> source, Action<TSource> action) {
foreach (var item in source) {
action(item);
yield return item;
}
}
并使用
_dc.EmailTemplates
.Apply(x => x.Body = RemoveUnwantedTags(x.Body))
.ToList();
这也可以用于多个成员,方法是
_dc.EmailTemplates
.Apply(x => {
x.Body = RemoveUnwantedTags(x.Body);
x.SomeOtherMember = SomeOtherFunction(x.SomeOtherMember);
})
.ToList();
我做了这个扩展方法(我知道现在没有异常检查等,一旦我确定功能确实正确就会添加):
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;
}
并在此上下文中使用(从字符串中删除不需要的标签条 html 标签):
_dc.EmailTemplates
.ChangeProperty(x=>x.Body,z=>RemoveUnwantedTags(z.Body))
.ToList();
但我不喜欢我必须使用双重 lambda,一个用于获取 属性 名称,然后一个用于执行函数。我不知道是我对 Expression<> 的工作原理缺乏了解,还是我遗漏了一些非常明显的东西,但非常感谢您的帮助!
类似于 ForEach
在 List<T>
中的使用方式,所需的功能可以简化为
public static IEnumerable<TSource> Apply<TSource>(this IEnumerable<TSource> source, Action<TSource> action) {
foreach (var item in source) {
action(item);
yield return item;
}
}
并使用
_dc.EmailTemplates
.Apply(x => x.Body = RemoveUnwantedTags(x.Body))
.ToList();
这也可以用于多个成员,方法是
_dc.EmailTemplates
.Apply(x => {
x.Body = RemoveUnwantedTags(x.Body);
x.SomeOtherMember = SomeOtherFunction(x.SomeOtherMember);
})
.ToList();