Linq中使用Left Join 和 Right Join
生活随笔
收集整理的這篇文章主要介紹了
Linq中使用Left Join 和 Right Join
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址:http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html
準備一些測試數據,如下:
?
use Test Create table Student( ID int identity(1,1) primary key, [Name] nvarchar(50) not null )Create Table Book( ID int identity(1,1) primary key, [Name] nvarchar(50)not null, StudentID int not null )
insert into Student values('張三') insert into Student values('李四') insert into Student values('王五') select * from student
--張三借的書 insert into Book values('紅樓',1) insert into Book values('大話紅樓',1)
--李四借的書 insert into Book values('三國',2)
--王五沒借書 --一本錯誤的記錄 insert into Book values('錯誤時怎樣練成的',111)
--左連接 select s.name,b.name from student as s left join Book as b on s.id=b.studentid
--右連接 select s.name,b.name from student as s right join Book as b on s.id=b.studentid
?
要用Linq實現左連接,寫法如下
?
DataClasses1DataContext db = new DataClasses1DataContext(); var leftJoinSql = from student in db.Student join book in db.Book on student.ID equals book.StudentID into temp from tt in temp.DefaultIfEmpty() select new { sname= student.Name, bname = tt==null?"":tt.Name//這里主要第二個集合有可能為空。需要判斷 };?
?
?
?
用Linq實現右連接,寫法如下
?
?
DataClasses1DataContext db=new DataClasses1DataContext(); var rightJoinSql = from book in db.Book join stu in db.Student on book.StudentID equals stu.ID into joinTemp from tmp in joinTemp.DefaultIfEmpty() select new { sname=tmp==null?"":tmp.Name, bname=book.Name};
?
?
參考資料:http://developer.51cto.com/art/200909/152189.htm
http://hi.baidu.com/thinsoft/blog/item/83fb1e9089cc7186a877a4b1.html
http://apps.hi.baidu.com/share/detail/12540006
http://www.winu.cn/space-14160-do-blog-id-25172.html
轉載于:https://www.cnblogs.com/xbzhu/p/7373155.html
總結
以上是生活随笔為你收集整理的Linq中使用Left Join 和 Right Join的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决远程连接mysql错误1130
- 下一篇: Design verification经