gpt4 book ai didi

c# - IQueryable.Where() 适合表达式在哪里?

转载 作者:行者123 更新时间:2023-12-01 21:37:19 24 4
gpt4 key购买 nike

我对 .NET 中的表达式 的经验非常少,这就是为什么我宁愿问你们。我该怎么办 - 请参阅下面的评论:

using P = Myclass;
..
System.Linq.Expressions.Expression<Func<P, bool>> myExpression = null;
..
myExpression1 = x => foo1 == true && foo2 == false;
myExpression2 = x => ... ;
..
BinaryExpression resultExpression = System.Linq.Expressions.Expression.OrElse(myExpression1, myExpression2);
..
IQueryable<P> l = l.Where(?resultExpression?); // how to transform BinaryExpression to the suitable type?

谢谢

最佳答案

你不能用这种方式将 lambda 组合在一起。你确实想将 lambda 体“或”在一起。这是一种方法:

public static Expression<Func<T, bool>> OrTheseFiltersTogether<T>( 
this IEnumerable<Expression<Func<T, bool>>> filters)
{
Expression<Func<T, bool>> firstFilter = filters.FirstOrDefault();
if (firstFilter == null)
{
Expression<Func<T, bool>> alwaysTrue = x => true;
return alwaysTrue;
}

var body = firstFilter.Body;
var param = firstFilter.Parameters.ToArray();
foreach (var nextFilter in filters.Skip(1))
{
var nextBody = Expression.Invoke(nextFilter, param);
body = Expression.OrElse(body, nextBody);
}
Expression<Func<T, bool>> result = Expression.Lambda<Func<T, bool>>(body, param);
return result;
}

然后:

Expression<Func<P, bool>> myFilter1 = x => foo1 == true && foo2 == false;  
Expression<Func<P, bool>> myFilter2 = x => ... ;
..
List<Expression<Func<P, bool>>> filters = new List<Expression<Func<P, bool>>>();
filters.Add(myfilter1);
filters.Add(myfilter2);
..
Expression<Func<P, bool>> resultFilter = filters.OrTheseFiltersTogether();
IQueryable<P> query = query.Where(resultFilter);

关于c# - IQueryable<T>.Where() 适合表达式在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4429956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com