• LINQ基础—Join子句


    LINQ基础—Join子句

    一、简介

    使用join子句可以将来自不同源序列并且在对象模型中没有直接关系的元素相关联,唯一的要求是每个源中的元素需要共享某个可以进行比较以判断是否相等的值,join子句使用特殊的equals关键字比较指定的键是否相等。

    二、案例

    内部连接

    var innerJoinQuery =
                  from category in categories
                  join prod in products on category.ID equals prod.CategoryID
                          select new { ProductName = prod.Name, Category = category.Name };

    分组连接

    var innerGroupJoinQuery =
     from category in categories
     join prod in products on category.ID equals prod.CategoryID
     into prodGroup
     select new { CategoryName = category.Name, Products = prodGroup };

    左外部连接

    var leftOuterJoinQuery =
                 from category in categories
                 join prod in products on category.ID equals prod.CategoryID
                 into prodGroup
                         from item in prodGroup.DefaultIfEmpty(new Product{Name =
                 string.Empty, CategoryID = 0})
                         select new { CatName = category.Name, ProdName = item.Name };

    分析:

    在左外连接中,将返回左侧源序列中的所有元素,即使它们在右侧序列中没有匹配的元素也是如此。
    若要在Linq中执行左外连接,请将DefaultIfEmpty方法与分组连接结合起来,以指定要在某个元素不具有匹配元素时产生的默认右侧元素,可以使用null作为任何引用类型的默认值。也可以指定用户定义的默认类型。


    技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
    我创建了一个.NET开发交流群,用于分享学习心得和讨论相关技术难题。欢迎有兴趣的小伙伴扫码入群,相互学习!

  • 相关阅读:
    cve-2019-1388复现+烂土豆+CVE-2019-0803
    子父域控双向信任
    黄金票据 白银票据 ms14068
    joomla3.4.6 rce 分析与复现
    主键索引跟唯一索引的区别
    hash 跟B+tree的区别
    MySQL数据库有几种索引?分别是什么?
    什么是事务?事务有什么特性?分别是什么?
    MySQL建立索引的原则
    什么是索引?索引的作用是什么?
  • 原文地址:https://www.cnblogs.com/wml-it/p/14837159.html
Copyright © 2020-2023  润新知