C# Linq PredicateBuilder - 多个 OR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/877034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:07:19  来源:igfitidea点击:

Linq PredicateBuilder - Multiple ORs

c#linq

提问by Duncan

I'm trying to use the PredicateBuilder, as described here - http://www.albahari.com/nutshell/predicatebuilder.aspx

我正在尝试使用 PredicateBuilder,如下所述 - http://www.albahari.com/nutshell/predicatebuilder.aspx

The following code

以下代码

var predicate = PredicateBuilder.False<StreetDTO>();

        predicate = predicate.Or(p => p.Locality.Contains(criteria.Locality));
        predicate = predicate.Or(p => p.Name.Contains(criteria.Name));
        predicate = predicate.Or(p => p.Town.Contains(criteria.Town));

        List<StreetDTO> streetData = StreetData.Instance();

        var streetList = from street in streetData.Where(predicate)
                         select street;

as far as I see this shouldwork, according to the example

根据示例,据我所知,这应该有效

var newKids  = Product.ContainsInDescription ("BlackBerry", "iPhone");

var classics = Product.ContainsInDescription ("Nokia", "Ericsson")
                      .And (Product.IsSelling());
var query =
  from p in Data.Products.Where (newKids.Or (classics))
  select p;

but all I get is

但我得到的只是

Error 1 The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

错误 1 ​​无法从用法推断方法“System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)”的类型参数。尝试明确指定类型参数。

I'm trying to gain some understanding in LINQ 'on-the-job', so apologies if this is a simple question.

我试图在 LINQ 'on-the-job' 中获得一些理解,所以如果这是一个简单的问题,我很抱歉。

采纳答案by Marc Gravell

Ah; your list is using IEnumerable<T>extension methods (rather than IQueryable<T>) - try:

啊; 您的列表正在使用IEnumerable<T>扩展方法(而不是IQueryable<T>) - 尝试:

var streetList = from street in streetData.AsQueryable().Where(predicate)
                 select street;

回答by bruno conde

Try compiling your predicate:

尝试编译您的谓词:

var streetList = from street in streetData.Where(predicate.Compile())
                 select street;