Linq允许使用join关键字或使用表达内部联接
SelectMany()(即来自关键字的几个)带有where关键字:
SelectMany()(即来自关键字的几个)带有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是有目的的,
与其他风格相比,有一种风格的性能优势?
解决方法
对于本地查询,由于其键控查找为
Athari mentioned,Join更有效,但是对于LINQ to sql(L2S),您将获得更多来自SelectMany的里程数.在L2S中,SelectMany最终在生成的sql中使用某种类型的sql连接,具体取决于您的查询.
看看问题11& 12#the LINQ Quiz by Joseph / Ben Albahari,C#4.0的作者.它们显示了不同类型连接的样本,并指出:
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为您提供的灵活性,具体取决于您配置数据所需的方式.