LINQ基础之Join和UNION子句

 

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作为任何引用类型的默认值。也可以指定用户定义的默认类型。

 

UNION子句

一、简介

Union返回并集,并集是指位于两个集合中任一集合的唯一的元素(自动去重复了)。在LINQ中UNION默认是去重的,没有UNION ALL 语句,不去重用CONCAT()。

二、案例

1.查询语句写法

Union会去除重复项,相当于SQL的Union

var q = (from c in db.Customers
       select c.Country
         ).Union(from e in db.Employees
                 select e.Country
         );

相当于

var q1 = from s in db.Student
                      where s.ID < 3
                      select s;
var q2 = from s in db.Student
                      where s.ID < 5
                      select s;

//去掉重复的
var q = q1.Union(q2);
var r = q.ToList();//ToList之后,会把数据查出来在内存中操作

如果不去重,用Concat()

//Concat不会去除重复项目,相当于SQL的Union All;
//不去掉重复的 相当于union all,
var q3 = q1.Concat(q2);
var r3 = q3.ToList()

2.另一种写法

var q = db.Customers.Union(db.Employees).select(d=>d.Country);

关于LINQ使用Join和UNION子句的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程宝库

 Intersect子句一、简介Intersect返回交集,交集是指同时出现在两个集合中的元素,和数据库中的Intersect方法实现功能一样。二、案例var ...