这篇文章介绍了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子句的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
本文标题为:LINQ基础之Join和UNION子句


基础教程推荐
- 使用c#从分隔文本文件中插入SQL Server表中的批量数据 2023-11-24
- C# – NetUseAdd来自Windows Server 2008和IIS7上的NetApi32.dll 2023-09-20
- c#中利用Tu Share获取股票交易信息 2023-03-03
- 京东联盟C#接口测试示例分享 2022-12-02
- C#通过GET/POST方式发送Http请求 2023-04-28
- C#中类与接口的区别讲解 2023-06-04
- C# Winform实现石头剪刀布游戏 2023-01-11
- c#读取XML多级子节点 2022-11-05
- Unity shader实现多光源漫反射以及阴影 2023-03-04
- C#集合查询Linq在项目中使用详解 2023-06-09