具有 LINQ 扩展方法的多个 WHERE 子句 [英] Multiple WHERE Clauses with LINQ extension methods

查看:39
本文介绍了具有 LINQ 扩展方法的多个 WHERE 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 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 AND 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).

关于链接 .Where() 方法的注意事项:您可以将所有需要的 LINQ 方法链接在一起.像 .Where() 这样的方法实际上并不针对数据库执行(目前).他们推迟执行,直到计算出实际结果(例如使用 .Count().ToList()).因此,当您将多个方法链接在一起时(对 .Where() 的更多调用,可能是一个 .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.

这篇关于具有 LINQ 扩展方法的多个 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆