首页 > 代码库 > Linq to Entities基础之需要熟知14个linq关键字(from,where,select,group,let,on,by...)

Linq to Entities基础之需要熟知14个linq关键字(from,where,select,group,let,on,by...)

1.Linq基础

《1》 关键词: from,in,group,by,where.....

MSDN上总结的有14个关键词法。。。

from xxxx in xxxx select => 三个不可缺少的条件。。。 【最基础的框架】

 

第一:这是语法糖。。。
第二:能够往sql上靠近。。。 (为了更好的理解)

using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = from s in db.Students
select s;

foreach (var item in query)
{
Console.WriteLine(item.StudentID+","+item.StudentName);
}
}


where词法: 做筛选操作

var query = from s in db.Students
where s.StudentName != "nihao"
select s;


group,into,by 词法: 分组的基础框架

k,v的结构, v=>list

Dictionary<T,List<T>>

using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = from s in db.Students
group s by s.StudentName
into g // g:就是刚才说到的 k,v结构。。。 Dictionary<string,List<Student>>
select g;


foreach (var item in query)
{
var mykey = item.Key;

var myValue = http://www.mamicode.com/item.ToList();
}

}

orderby, ascending,descending. 在一起的。。。

using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = from s in db.Students
group s by s.StudentName
into g // g:就是刚才说到的 k,v结构。。。 Dictionary<string,List<Student>>
orderby g.Key descending
select g;


foreach (var item in query)
{
var mykey = item.Key;

var myValue = http://www.mamicode.com/item.ToList();
}
}


join词法。。。和 on ,equal,一起搭配使用的。。。因为我们需要做表的关联。。。


using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = from s in db.Students
join a in db.StudentAddresses
on s.StudentID equals a.StudentID
select new { s, a };

var list = query.ToList();
}

SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[RowVersion] AS [RowVersion],
[Extent2].[StudentID] AS [StudentID1],
[Extent2].[Address1] AS [Address1],
[Extent2].[Address2] AS [Address2],
[Extent2].[City] AS [City],
[Extent2].[State] AS [State]
FROM [dbo].[Student] AS [Extent1]
INNER JOIN [dbo].[StudentAddress] AS [Extent2] ON [Extent1].[StudentID] = [Extent2].[StudentID]

 

let词法: 临时变量


static void Main(string[] args)
{
using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = from s in db.Students
let namelength = s.StudentName.Length
select new { len = namelength, s };

var list2 = query.ToList();
}

var list = new string[] { "123", "3" };

foreach (var item in list)
{
var temp = item.Length; //这个temp就是let的功效

Console.WriteLine();
}
}

可以让这14个关键字随意组合,可以构成非常复杂的“表达式”。。。。嵌套,递归啊。。。。

 

《2》 扩展方法,IQueryable上面扩展方法。。。

Linq to Entities基础之需要熟知14个linq关键字(from,where,select,group,let,on,by...)