我有以下查询按需执行“ 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.
}
因此,我该如何执行相同的查询,但按需执行“ OR”(这样查询才有意义)?
最佳答案
您可以将IN
的传真用于LINQ:
var productCodeList = products.Select(p => p.Code).ToList();
query = query.Where(p => productCodeList.Contains(p.Code));
基本上是说:
SELECT *
FROM products
WHERE code IN (<list_of_codes>)