用linqPad帮助你快速学习LINQ

在这里我向大家推荐的一个具是LinqPad有了这个工具并熟练使用就可以很快学习并掌握linq

linqPad下载地址:http://www.linqpad.net/

它也自带了很多例子方便大家查询,linqPad支持object ,xml,sql ,  to linq这里我只讲一下sql to linq

好多同学不知道怎么用linq完成 left join ,inner join 等,这里我就用这个工具给大家实现一下

linqpad 会给我们同时生成lambda表达式,sql和IL 我一般情况下有linq的lambda不会的时候,就用Linqpad来调试得到结果

打开它的主页面看一下,点AddConnection 就可以添加数据库连接

 先在数据库里建一个库MyDataDemo两个表Classes和Student

create database 
MyDataDemo
go 
use MyDataDemo
go

drop table Student
create table Classes
(
    class_Id int ,
    class_Name varchar(100)
)
create table Student
(
    st_Id int,
    st_Name varchar(100),
    class_Id int
)

insert into Classes values(1,'OneC')
insert into Classes values(2,'TwoC')
insert into Classes values(3,'ThreeC')

insert into Student values(1,'xiaoMing',1)

insert into Student values(2,'zhangqiang',2)
insert into Student values(3,'lihong',3)

insert into Student values(4,'wangsi',1)
insert into Student values(5,'zhaoWu',1)
insert into Student values(6,'WangLiu',2)
数据库里建两个表

 我们在linqPad的query标签里把Language 选择为c# Expression ,把Connection 选择数据MyDataDemo 就是我们上边建好的数据库如图

先看一下Left Join

我们在面版里输入最基本的Linq表达式 点执行或者F5

from stu in Students
join cla in Classes
on stu.Class_Id equals cla.Class_Id
into MyJoin
from grp in MyJoin.DefaultIfEmpty()
select new {ClassId=grp.Class_Id,Class_Name=grp.Class_Name,st_Name =stu.St_Name}

看一下linqPad给我们显示的结果
sql结果 是判断我们的Linq是不是正确的

看它是left outer join(left join 是Left outer join 和简写) 证明我们是正确的

SELECT [t1].[class_Id] AS [ClassId], [t1].[class_Name] AS [Class_Name], [t0].[st_Name]
FROM [Student] AS [t0]
LEFT OUTER JOIN [Classes] AS [t1] ON [t0].[class_Id] = [t1].[class_Id]

最强的是它还给我们生成lambda表达式

Students
   .GroupJoin (
      Classes, 
      stu => stu.Class_Id, 
      cla => cla.Class_Id, 
      (stu, MyJoin) => 
         new  
         {
            stu = stu, 
            MyJoin = MyJoin
         }
   )
   .SelectMany (
      temp0 => temp0.MyJoin.DefaultIfEmpty (), 
      (temp0, grp) => 
         new  
         {
            ClassId = grp.Class_Id, 
            Class_Name = grp.Class_Name, 
            st_Name = temp0.stu.St_Name
         }
   )

再看一下inner join

//inner join 
from stu in Students
join cla in Classes
on stu.Class_Id equals cla.Class_Id
select new {ClassId=cla.Class_Id,Class_Name=cla.Class_Name,st_Name =stu.St_Name}

看一下sql结果我们是不是正确的

SELECT [t1].[class_Id] AS [ClassId], [t1].[class_Name] AS [Class_Name], [t0].[st_Name]
FROM [Student] AS [t0]
INNER JOIN [Classes] AS [t1] ON [t0].[class_Id] = [t1].[class_Id]

正确
再看一下lambda表达式

Students
   .Join (
      Classes, 
      stu => stu.Class_Id, 
      cla => cla.Class_Id, 
      (stu, cla) => 
         new  
         {
            ClassId = cla.Class_Id, 
            Class_Name = cla.Class_Name, 
            st_Name = stu.St_Name
         }
   )

就讲到这里大家可以多学习一下这个工具

 

posted @ 2013-11-26 10:19  li-peng  阅读(16952)  评论(13编辑  收藏  举报