Linq 允许通过使用 join 关键字或使用
SelectMany()(即几个 from 关键字)和 where 关键字:
var personsToState = from person in persons
join state in statesOfUS
on person.State equals state.USPS
select new { person, State = state.Name };
foreach (var item in personsToState)
{
System.Diagnostics.Debug.WriteLine(item);
}
// The same query can be expressed with the query operator SelectMany(), which is
// expressed as two from clauses and a single where clause connecting the sequences.
var personsToState2 = from person in persons
from state in statesOfUS
where person.State == state.USPS
select new { person, State = state.Name };
foreach (var item in personsToState2)
{
System.Diagnostics.Debug.WriteLine(item);
}
我的问题:什么时候使用 join-style 是有目的的,什么时候使用 where-style,
一种风格比另一种风格有性能优势吗?
最佳答案
本地查询 Join
由于其键控查找为 Athari mentioned,因此效率更高,但是对于 LINQ to SQL (L2S),您将从 SelectMany
中获得更多 yield 。 .在 L2S 中 SelectMany
最终根据您的查询在生成的 SQL 中使用某种类型的 SQL 连接。
查看 the LINQ Quiz 的问题 11 和 12作者 Joseph/Ben Albahari,C# 4.0 In a Nutshell 的作者。他们展示了不同类型连接的示例,并指出:
With LINQ to SQL, SelectMany-based joins are the most flexible, and can perform both equi and non-equi joins. Throw in DefaultIfEmpty, and you can do left outer joins as well!
此外,Matt Warren 有一篇关于此主题的详细博客文章,因为它与
IQueryable
有关。/SQL 在这里:LINQ: Building an IQueryable provider - Part VII .回到您使用哪个查询的问题,您应该使用更易读的查询,并允许您轻松表达自己并清楚地构建您的最终目标。除非您正在处理大型集合并分析了这两种方法,否则性能不应成为最初的关注点。在 L2S 中,您必须考虑灵活性
SelectMany
根据您需要配对数据的方式为您提供。
关于linq - 何时更喜欢用 SelectMany() 表示的连接而不是 Linq 中用 join 关键字表示的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025871/