问题描述
我有一个LINQ查询,看起来像以下内容:
I have a LINQ query that looks like the following:
DateTime today = DateTime.UtcNow;
var results = from order in context.Orders
where ((order.OrderDate <= today) && (today <= order.OrderDate))
select order;
我想学习/了解LINQ。在某些情况下,我需要增加两个额外的WHERE子句。在努力做到这一点,我使用的:
I am trying to learn / understand LINQ. In some cases, I need to add two additional WHERE clauses. In an effort to do this, I'm using:
if (useAdditionalClauses)
{
results = results.Where(o => o.OrderStatus == OrderStatus.Open) // Now I'm stuck.
}
正如你所看到的,我知道如何添加一个额外的WHERE子句。但我怎么添加多个?举例来说,我想补充
As you can see, I know how to add an additional WHERE clause. But how do I add multiple? For instance, I'd like to add
WHERE o.OrderStatus == OrderStatus.Open和o.CustomerID ==的customerID
我以前的查询。我如何做到这一点使用扩展方法?
to my previous query. How do I do this using extension methods?
感谢您!
推荐答案
两种方式:
results = results.Where(o => (o.OrderStatus == OrderStatus.Open) &&
(o.CustomerID == customerID));
或
results = results.Where(o => (o.OrderStatus == OrderStatus.Open))
.Where(o => (o.CustomerID == customerID));
我通常更喜欢后者。但它是值得分析的SQL服务器检查查询执行,看看哪一个执行对你的数据更好(如果有任何差别)。
I usually prefer the latter. But it's worth profiling the SQL server to check the query execution and see which one performs better for your data (if there's any difference at all).
有关链接的的注意事项。凡()
的方法:你可以你要链接的所有的LINQ的方法。像方法。凡()
实际上并不对数据库执行(还)。他们直到实际结果计算(如以 .Count之间的()
或 .ToList()
)。所以,要链接的多种方法(多次调用。凡()
,也许一个 .OrderBy()
或诸如此类的话,等等),他们建立了所谓的一个。这整个树是在时机成熟时,以评估它什么获取对数据源执行。
A note about chaining the .Where()
methods: You can chain together all the LINQ methods you want. Methods like .Where()
don't actually execute against the database (yet). They defer execution until the actual results are calculated (such as with a .Count()
or a .ToList()
). So, as you chain together multiple methods (more calls to .Where()
, maybe an .OrderBy()
or something to that effect, etc.) they build up what's called an expression tree. This entire tree is what gets executed against the data source when the time comes to evaluate it.
这篇关于多WHERE子句使用LINQ扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!