Linq之关键字基本查询

子句说明
from 指定数据源和范围变量(类似于迭代变量)。
where 根据一个或多个由逻辑“与”和逻辑“或”运算符(&& 或 ||)分隔的布尔表达式筛选源元素。
select 指定当执行查询时返回的序列中的元素将具有的类型和形式。
group 按照指定的键值对查询结果进行分组。
into 提供一个标识符,它可以充当对 join、group 或 select 子句的结果的引用。
orderby 基于元素类型的默认比较器按升序或降序对查询结果进行排序。
join 基于两个指定匹配条件之间的相等比较来联接两个数据源。
let 引入一个用于存储查询表达式中的子表达式结果的范围变量。
in join 子句中的上下文关键字。
on join 子句中的上下文关键字。
equals join 子句中的上下文关键字。
by group 子句中的上下文关键字。
ascending orderby 子句中的上下文关键字。
descending orderby 子句中的上下文关键字。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1、from关键字

需求查询出班级信息

Linq:from g in Grades select g

对应Lambda:Grades.Select (g => g)

对应SQL:select * from Grade

2、where关键字

需求查询出语文成绩大于90的成绩表ID

Linq:from s in ScoreInfo where s.Chinese>90 select s.ScoreId

对应Lambda:ScoreInfo .Where (s => (s.Chinese > 90)) .Select (s => s.ScoreId)

对应SQL:select ScoreId from ScoreInfo where Chinese>90

3、group关键字

需求查询以工资为500的进行分组

Linq:from s in SalaryInfo group s by s.Salary

对应Lambda:SalaryInfo .GroupBy (s => s.Salary)

对应SQL:select Salary from  SalaryInfo group by Salary 

4、join关键字

需求根据成绩表id,对学生表进行关键

Linq: from s in StudentInfo join c in ScoreInfo on s.ScoreId equals  c.ScoreId  select new {s, c}

对应Lambda:StudentInfo
   .Join (
      ScoreInfo,
      s => s.ScoreId,
      c => c.ScoreId,
      (s, c) =>
         new 
         {
            s = s,
            c = c
         }
   )

对应SQL:

SELECT [t0].[StudentId], [t0].[ScoreId], [t0].[SName], [t0].[SAge], [t0].[SSex], [t0].[SPhone], [t1].[ScoreId] AS [ScoreId2], [t1].[Chinese], [t1].[Math], [t1].[English]

FROM [StudentInfo] AS [t0]
INNER JOIN [ScoreInfo] AS [t1] ON [t0].[ScoreId] = [t1].[ScoreId]

5、GroupJoin关键字

GroupJoin操作符常应用于返回“主键对象-外键对象集合”形式的查询,如成绩表主键---该主键下的所有学生信息

Linq:from s in ScoreInfo
join c in StudentInfo on s.ScoreId equals c.ScoreId into g
select new {s.ScoreId, list = g}

对应Lambda:ScoreInfo
   .GroupJoin (
      StudentInfo,
      s => s.ScoreId,
      c => c.ScoreId,
      (s, g) =>
         new 
         {
            ScoreId = s.ScoreId,
            list = g
         }
   )

对应SQL:

SELECT [t0].[ScoreId], [t1].[StudentId], [t1].[ScoreId] AS [ScoreId2], [t1].[SName], [t1].[SAge], [t1].[SSex], [t1].[SPhone], (
SELECT COUNT(*)
FROM [StudentInfo] AS [t2]
WHERE [t0].[ScoreId] = [t2].[ScoreId]
) AS [value]
FROM [ScoreInfo] AS [t0]
LEFT OUTER JOIN [StudentInfo] AS [t1] ON [t0].[ScoreId] = [t1].[ScoreId]
ORDER BY [t0].[ScoreId], [t1].[StudentId]




 




   

原文地址:https://www.cnblogs.com/qzxj/p/7065230.html