一、简介
使用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作为任何引用类型的默认值。也可以指定用户定义的默认类型。
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub: https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang