1. 程式人生 > >Linq之關鍵字基本查詢

Linq之關鍵字基本查詢

返回 大於 sce 布爾表達式 操作符 默認 lec desc 邏輯

子句說明
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]







Linq之關鍵字基本查詢