【发布时间】:2019-02-10 21:18:30
【问题描述】:
您好,我尝试从由 or 组合的列表中生成单个 Func。
var funcs = new List<Func<User, bool>>()
{
(u) => u.Id.Equals(entityToFind.Id),
(u) => u.UserName == entityToFind.UserName,
(u) => u.Email == entityToFind.Email
};
//TODO: Some magic that funs is euqaly to that:
Func<User, bool> func = (u) => u.Id.Equals(entityToFind.Id) || u.UserName == entityToFind.UserName || u.Email == entityToFind.Email;
我也尝试过使用表达式,就像这样:
private Dictionary<string, Expression<Func<User, bool>>> private Dictionary<string, Expression<Func<User, bool>>> test(User entityToFind)
{
return new Dictionary<string, Expression<Func<User, bool>>>() {
{"Id", (u) => u.Id.Equals(entityToFind.Id) },
{"Name", (u) => u.UserName == entityToFind.UserName },
{"Email", (u) => u.Email == entityToFind.Email }
};
}
public static Expression<Func<T, bool>> ToOrExpression<T>(this Dictionary<string, Expression<Func<T, bool>>> dict)
{
var expressions = dict.Values.ToList();
if (!expressions.Any())
{
return t => true;
}
var delegateType = typeof(Func<T, bool>)
.GetGenericTypeDefinition()
.MakeGenericType(new[]
{
typeof(T),
typeof(bool)
}
);
var tfd = Expression.OrElse(expressions[0], expressions[1]);
var combined = expressions
.Cast<Expression>()
.Aggregate( (e1, e2) => Expression.OrElse(e1, e2) );
return (Expression<Func<T, bool>>)Expression.Lambda(delegateType, combined);
}
test(entityToFind).ToOrExpression();
但是我会得到以下错误:
二元运算符 OrElse 没有为类型 'System.Func2[Models.User,System.Boolean]' and
'System.Func2[Models.User,System.Boolean]' 定义
【问题讨论】:
-
这是否适用于实体框架?
-
@DavidG 是的,对于 MongoClient
-
所以你已经使用
Func而不是Expression处于一个糟糕的前提 -
我将使用:return u => generatedFunc(entityToFind);最后;)
-
@DavidG 但如果您知道使用表达式的解决方案,我也可以这样做
标签: linq generics asp.net-core .net-core func