Linq 基础查询

来源:互联网 发布:长春外国语学校 知乎 编辑:程序博客网 时间:2024/05/21 06:53


Linq查询语句编写工具可以用LinqPad,挺好用的

一下是我自己学习Linq to SQL的查询语句

//基本查询
/*from c in WorkFlows
select c*/

//带条件查询
/*from c in WorkFlows
where c.Pid==1
select c*/

//查询显示不同的列
/*from c in WorkFlows
select new
{
   c.ID,
   c.WorkFlowName
}*/

//排序
/*from c in WorkFlows
orderby c.ID descending
select c*/

//去除某个字段的重复
/*(from c in WorkFlows
where c.Pid == 1
select c.Step).Distinct()*/

//带条件的分组查询
/*from c in WorkFlows
where c.Pid == 1
group c by c.Step into g
select g*/


/*from c in Cities
where c.State == "北京市"
select c*/

//分组后查询最大的 Min或最小的
/*from c in Cities
group c by c.State into g
select new
{
   g.Key,        
   MaxId = g.Max(c => c.Id),
}*/

//查询包含数组中的数据
/*
from c in Cities
where (new string[] { "河南省", "北京市" }).Contains(c.State)
select c*/

/*
from c in Cities
orderby c.Id descending,c.Sz_code ascending
select c*/

//查询Content字段包含“西”的和字段State以“河”开头的数据 并连接
/*
(from c in Cities
where c.Content.Contains("西")
select c).Union
(from c in Cities
where c.State.StartsWith("河")
select c)*/

//子查询
/*from p in PersonTables
select new
{
   ID = p.ID,
   CityID = (from c in Cities where c.Id == p.CityID select c.Content),
   PersonName=p.PersonName,
   Sex = p.Sex
}*/

//左连接查询
/*from p in PersonTables
join c in Cities   //关联表
    on p.CityID equals c.Id
    into pro
    from x in pro.DefaultIfEmpty()  //显示左边没有关联的数据,如果不用DefaultIfEmpty() 则不会显示左边表的全部数据
//from x in pro
select new
{
   ID = p.ID,
   PersonName = p.PersonName,
   Sex = p.Sex,
   Content = x.Content==null ? "不存在" :x.Content
}*/

//多表关联join查询
/*
from c in Cities
join p in PersonTables  //关联第一个表
    on c.Id equals p.CityID
    into cro
    from x in cro.DefaultIfEmpty()
join w in WorkFlows  //关联第二个表
    on x.ID equals w.ID
    into xrw
    from s in xrw.DefaultIfEmpty()
select new
{
   Id = c.Id,
   State = c.State,
   Content = c.Content,
   SzCode = c.Sz_code,
   Name = x.PersonName,
   Sex = x.Sex,
   WorkFlowName= s.WorkFlowName,
   Step = s.Step
}
*/

原创粉丝点击