加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

何时更喜欢用SelectMany()表示的连接超过Linq中用join关键字表示

发布时间:2020-12-12 06:33:31 所属栏目:MsSql教程 来源:网络整理
导读:Linq允许使用join关键字或使用表达内部联接 SelectMany()(即来自关键字的几个)带有where关键字: var personsToState = from person in persons join state in statesOfUS on person.State equals state.USPS select new { person,State = state.Name };forea
Linq允许使用join关键字或使用表达内部联接
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为您提供的灵活性,具体取决于您配置数据所需的方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读