简体   繁体   English

“或”按需使用 Linq 到实体,我该怎么做?

[英]"OR" on-demand with Linq to Entities, how can i do it?

I have the following query that performs a "AND" on-demand:我有以下按需执行“AND”的查询:

var products = // Selecting a list of products in anywhere based in a filter...

foreach (var product in products)
{
    query = query.Where(p => p.Code == product.Code); // with this way, this query make no sense because this happens in any scenario, never a code can be more than one code.
}

So, how can i do the same query but performing a "OR" on-demand (so that the query makes sense)?那么,我如何才能执行相同的查询但按需执行“OR”(以便查询有意义)?

Using Contains :使用包含

var codes = products.Select(x => x.Code).ToArray();

query.Where(p => codes.Contains(p.Code));

You can use the facsimile of an IN for LINQ:您可以使用IN的传真 LINQ:

var productCodeList = products.Select(p => p.Code).ToList();

query = query.Where(p => productCodeList.Contains(p.Code));

It's basically saying:它基本上是在说:

SELECT   *
FROM     products
WHERE    code IN (<list_of_codes>)

Either use the Contains method ad Brad and Joe wrote, or (when that's not possible) use the PredicateBuilder:要么使用 Brad 和 Joe 编写的Contains方法,要么(如果不可能)使用PredicateBuilder:

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

foreach (var product in products)
{
    var code = product.Code;
    predicate = predicate.Or(p => p.Code == code);
}

var products dataContext.Products.Where(predicate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 C# 中创建按需 DynamoDB 表? - How can I create an On-Demand DynamoDB table in C#? 如何确保数据流块仅按需创建线程? - How can I make sure a dataflow block only creates threads on a on-demand basis? 如何实现从数据库(按需)加载配置值的 IConfigurationProvider? - How can I implement an IConfigurationProvider which loads config values from a database (on-demand)? 如何在 MEF 中动态按需加载插件? - How can plugins be loaded dynamically and on-demand in MEF? 如何在 Entity Framework LINQ To Entities 中进行联合? - How can I do a Union all in Entity Framework LINQ To Entities? 我如何进行连接两个实体的LINQ查询并选择其中一个实体上的“何处”? - How can I do a LINQ query joining two entities and select what a Where on one of the entities? 我如何使用清单 <string> 在Linq中以实体作为实体? - How can I use List<string> in Linq to Entities as Entities? 如何进行EF Linq查询,包括相关实体的子集 - How can I do an EF Linq query, including a subset of related entities Linq to Entities查询确实很慢。 我能做什么? - Linq to Entities query really slow. What can I do? Linq to实体:如何执行子查询 - Linq to entities: how to do a subquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM