我使用IQueryable来构建我的查询。
IQueryable<PropertyPosts> posts = context.PropertyPosts;
之后基于几个条件,我将 Where 子句附加到我的查询中,
if (item.ApartmentCondo == 1)
{
posts= posts.Where(x => x.name == item.name &&
x.PropertyType == PropertyType.ApartmentCondo );
}
if (item.House == 1)
{
posts= posts.Where(x => x.name == item.name &&
x.PropertyType == PropertyType.House );
}
注意:还有其他一些条件。
之后,当我执行以下查询时,
List<PropertyPosts> posts2 = posts.ToList();
以上所有 条件将被&#39;并且
。但相反,我需要Where条件为&#39; OR&#39;
这意味着我需要一种方法来附加几个Where条件,但所有这些条件都应该执行&#39; OR&#39;他们之间的条件。
我怎样才能做到这一点?是否有其他方式而不是使用&#39; 哪里&#39;?
答案 0 :(得分:2)
您可以使用以下documentation:
var predicate = PredicateBuilder.False<PropertyPosts>();
//predicate = predicate.OR(x=>x.SomeProperties == someValues);
//predicate = predicate.AND(x=>x.SomeOtherProperties == someOtherValues);
if (item.ApartmentCondo == 1)
{
predicate = predicate.OR(x => x.name == item.name &&
x.PropertyType == PropertyType.ApartmentCondo );
}
if (item.House == 1)
{
predicate = predicate.OR(x => x.name == item.name &&
x.PropertyType == PropertyType.House );
}
List<PropertyPosts> posts2 = posts.Where(predicate).ToList();
您可以将它用于您的案例:
var test= jQuery("#jqgrid").jqGrid('getGridParam', 'records');
答案 1 :(得分:2)
将您的if
条件移到Where:
posts = posts.Where(x => x.name == item.name &&
( (item.ApartmentCondo == 1 && x.PropertyType == PropertyType.ApartmentCondo)
|| (item.House == 1 && x.PropertyType == PropertyType.House) );
答案 2 :(得分:1)
试试这个。
posts= posts.Where(x => x.name == item.name &&
(
(item.ApartmentCondo == 1 && x.PropertyType == PropertyType.ApartmentCondo) ||
(item.House == 1 && x.PropertyType == PropertyType.House))
);
答案 3 :(得分:0)
很抱歉找到一个新的答案,但我的代表太少,无法发表评论。
真/假有效,但有点混乱,也会产生多个起点。我修改了代码并删除了True&lt; T&gt;和假&lt; T&gt;方法并为Create&lt; T&gt;创建了一个新的重载方法。
public static class PredicateBuilder
{
public const bool TreatEntireExpressionAsAnd = true;
public const bool TreatEntireExpressionAsOr = false;
public static Expression<Func<T, bool>> Create<T>(bool value = TreatEntireExpressionAsAnd) { return param => value; }
...