搜尋
首頁後端開發C#.Net教程SQL、LINQ和Lambda表達式

SQL、LINQ和Lambda表達式

Feb 23, 2017 am 10:05 AM
lambda


首先說說這三者完全是三種不同的東西,SQL是結構化查詢語言(Structured Query Language)簡稱,這大家再熟悉不過了,以下主要介紹LINQ和Lambda表達式的基本概念以及同一查詢這三者的不同實作。

簡單介紹

LINQ(Language Integrate Query)是語言整合查詢他在物件和資料之間建立一種對應的關係,可以使用存取記憶體物件的方式查詢資料集合。 LINQ查詢是C#中的一種語言建構。因此開發人員可以再C#程式碼來總結巢狀類似SQL語句的查詢表達式,進而實現資料查詢的功能。 LINQ也不是簡單地作為C#中嵌套查詢表達式,而是將查詢表達式作為C#的一種語法。
 在.NET類別庫中,LINQ相關類別庫都在System.Linq命名空間下,該命名空間提供支援使用LINQ進行查詢的類別和接口,其中最主要的是以下兩個類別和兩個介面。
 ※IEnumerable介面:它表示可以查詢的資料集合,一個查詢通常是逐一對集合中的元素進行篩選操作,傳回一個新的IEnumerable接口,用來保存查詢結果。
 ※IQueryable介面:他繼承IEnumerable接口,表示一個可以查詢的表達式目錄樹。
 ※Enumerable類別:它透過對IEnumerable提供擴充方法,實現LINQ標準查詢運算子。包括過路、導航、排序、查詢、聯結、求和、求最大值、求最小值等操作。
 ※Queryable類別:它透過對IQueryable提供擴充方法,實作LINQ標準查詢運算子。包括過路、導航、排序、查詢、聯結、求和、求最大值、求最小值等操作。
 Lambda表達式其實是一個匿名函數,它可以說是對LINQ的補充。由於LINQ查詢關鍵字和IEnumerable介面的方法之間有一個對應關係,但LINQ查詢運算式中可以使用的查詢功能很少。在實際開發中透過查詢結果或資料來源進行方法調用,從而進行更多的查詢操作。由於Lambda表達式是匿名函數,它可以賦值到一個委託,而在IEnumerable介面的方法中很多透過函數委託來實現自訂運算、條件等操作,所以Lambda表達式在LINQ中被廣泛使用。

比較實作

※查詢全部內容

1 查询Student表的所有记录。
2 select * from student
3 Linq:
4     from s in Students
5     select s
6 Lambda:
7     Students.Select( s => s)

※按列查詢

select sname,ssex,class from student 
3 Linq: 
4     from s in Students 
5     select new { 
6         s.SNAME, 
7         s.SSEX, 
8         s.CLASS
 9     }
 10 Lambda:
 11     Students.Select( s => new {
 12         SNAME = s.SNAME,SSEX = s.SSEX,CLASS = s.CLASS
 13     })

※distinct去重查詢

 查询教师所有的单位即不重复的Depart列。
2 select distinct depart from teacher
3 Linq:
4     from t in Teachers.Distinct()
5     select t.DEPART6 Lambda:
7     Teachers.Distinct().Select( t => t.DEPART)

※兩個區間內查詢

1 查询Score表中成绩在60到80之间的所有记录。
 2 select * from score where degree between 60 and 80
 3 Linq: 
 4     from s in Scores 
 5     where s.DEGREE >= 60 && s.DEGREE < 80
 6     select s 
 7 Lambda: 
 8     Scores.Where( 
 9         s => (
 10                 s.DEGREE >= 60 && s.DEGREE < 80
 11              )
 12     )

※在一個範圍內查詢

 select * from score where degree in (85,86,88)
 2 Linq:
 3     from s in Scores
 4     where (
 5             new decimal[]{85,86,88}
 6           ).Contains(s.DEGREE)
 7     select s
 8 Lambda:
 9     Scores.Where( s => new Decimal[] {85,86,88}.Contains(s.DEGREE))

※或關係查詢

 查询Student表中"95031"班或性别为"女"的同学记录。
 2 select * from student where class =&#39;95031&#39; or ssex= N&#39;女&#39;
 3 Linq:
 4     from s in Students
 5     where s.CLASS == "95031"
 6        || s.CLASS == "女"
 7     select s
 8 Lambda:
 9     Students.Where(s => ( s.CLASS == "95031" || s.CLASS == "女"))

※排序

 以Class降序查询Student表的所有记录。
 2 select * from student order by Class DESC
 3 Linq:
 4     from s in Students
 5     orderby s.CLASS descending
 6     select s
 7 Lambda:
 8     Students.OrderByDescending(s => s.CLASS)

※行數查詢

 select count(*) from student where class = &#39;95031&#39;
 2 Linq: 
 3     (    from s in Students 
 4         where s.CLASS == "95031"
 5         select s 
 6     ).Count() 
 7 Lambda: 
 8     Students.Where( s => s.CLASS == "95031" ) 
 9                 .Select( s => s)
 10                     .Count()

※平均值查詢

 查询&#39;3-105&#39;号课程的平均分。
 2 select avg(degree) from score where cno = &#39;3-105&#39;
 3 Linq: 
 4     ( 
 5         from s in Scores 
 6         where s.CNO == "3-105"
 7         select s.DEGREE 
 8     ).Average() 
 9 Lambda:
 10     Scores.Where( s => s.CNO == "3-105")
 11             .Select( s => s.DEGREE)

※潛逃查詢

查询Score表中的最高分的学生学号和课程号。
 2 select distinct s.Sno,c.Cno from student as s,course as c ,score as sc 
 3 where s.sno=(select sno from score where degree = (select max(degree) from score)) 
 4 and c.cno = (select cno from score where degree = (select max(degree) from score)) 
 5 Linq: 
 6     ( 
 7         from s in Students 
 8         from c in Courses 
 9         from sc in Scores
 10         let maxDegree = (from sss in Scores
 11                         select sss.DEGREE
 12                         ).Max()
 13         let sno = (from ss in Scores
 14                 where ss.DEGREE == maxDegree
 15                 select ss.SNO).Single().ToString()
 16         let cno = (from ssss in Scores
 17                 where ssss.DEGREE == maxDegree
 18                 select ssss.CNO).Single().ToString()
 19         where s.SNO == sno && c.CNO == cno
 20         select new {
 21             s.SNO,
 22             c.CNO
 23         }
 24     ).Distinct()

※分組

 查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
 2 select avg(degree) from score where cno like &#39;3%&#39; group by Cno having count(*)>=5
 3 Linq: 
 4         from s in Scores 
 5         where s.CNO.StartsWith("3") 
 6         group s by s.CNO 
 7         into cc 
 8         where cc.Count() >= 5
 9         select cc.Average( c => c.DEGREE)
 10 Lambda:
 11     Scores.Where( s => s.CNO.StartsWith("3") )
 12             .GroupBy( s => s.CNO )
 13               .Where( cc => ( cc.Count() >= 5) )
 14                 .Select( cc => cc.Average( c => c.DEGREE) )
 15 Linq: SqlMethod
 16 like也可以这样写:
 17     s.CNO.StartsWith("3") or SqlMethods.Like(s.CNO,"%3")

※分組過濾

查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
 2 select avg(degree) from score where cno like &#39;3%&#39; group by Cno having count(*)>=5
 3 Linq: 
 4         from s in Scores 
 5         where s.CNO.StartsWith("3") 
 6         group s by s.CNO 
 7         into cc 
 8         where cc.Count() >= 5
 9         select cc.Average( c => c.DEGREE)
 10 Lambda:
 11     Scores.Where( s => s.CNO.StartsWith("3") )
 12             .GroupBy( s => s.CNO )
 13               .Where( cc => ( cc.Count() >= 5) )
 14                 .Select( cc => cc.Average( c => c.DEGREE) )
 15 Linq: SqlMethod
 16 like也可以这样写:
 17     s.CNO.StartsWith("3") or SqlMethods.Like(s.CNO,"%3")

※多表聯合查詢

 select sc.sno,c.cname,sc.degree from course as c,score as sc where c.cno = sc.cno
 2 Linq: 
 3     from c in Courses 
 4     join sc in Scores 
 5     on c.CNO equals sc.CNO
 6     select new 
 7     { 
 8         sc.SNO,c.CNAME,sc.DEGREE
 9     }
 10 Lambda:
 11     Courses.Join ( Scores, c => c.CNO,
 12                              sc => sc.CNO,
 13                              (c, sc) => new
 14                                         {
 15                                             SNO = sc.SNO,
 16                                             CNAME = c.CNAME,
 17                                             DEGREE = sc.DEGREE
 18                                         })
 19                 .Average()

以上內容是本人查閱資料做的一些整理和總結,有不足之處請大家批評指正!

首先說這三者完全是三種不同的東西,SQL是結構化查詢語言(Structured Query Language)簡稱,這大家再熟悉不過了,以下主要介紹LINQ和Lambda表達式的基本概念以及同一查詢這三者的不同實現。

简单介绍

LINQ(Language Integrate Query)是语言集成查询他在对象和数据之间建立一种对应的关系,可以使用访问内存对象的方式查询数据集合。LINQ查询是C#中的一种语言构造。因此开发人员可以再C#代码汇总嵌套类似于SQL语句的查询表达式,从而实现数据查询的功能。LINQ也不是简单地作为C#中嵌套查询表达式,而是将查询表达式作为C#的一种语法。
 在.NET类库中,LINQ相关类库都在System.Linq命名空间下,该命名空间提供支持使用LINQ进行查询的类和接口,其中最主要的是以下两个类和两个接口。
 ※IEnumerable接口:它表示可以查询的数据集合,一个查询通常是逐个对集合中的元素进行筛选操作,返回一个新的IEnumerable接口,用来保存查询结果。
 ※IQueryable接口:他继承IEnumerable接口,表示一个可以查询的表达式目录树。
 ※Enumerable类:它通过对IEnumerable提供扩展方法,实现LINQ标准查询运算符。包括过路、导航、排序、查询、联接、求和、求最大值、求最小值等操作。
 ※Queryable类:它通过对IQueryable提供扩展方法,实现LINQ标准查询运算符。包括过路、导航、排序、查询、联接、求和、求最大值、求最小值等操作。
 Lambda表达式实际上是一个匿名函数,它可以说是对LINQ的补充。由于LINQ查询关键字和IEnumerable接口的方法之间有一个对应关系,但是LINQ查询表达式中可以使用的查询功能很少。在实际开发中通过查询结果或数据源进行方法调用,从而进行更多的查询操作。由于Lambda表达式是匿名函数,它可以赋值到一个委托,而在IEnumerable接口的方法中很多通过函数委托来实现自定义运算、条件等操作,所以Lambda表达式在LINQ中被广泛使用。

对比实现

※查询全部内容

1 查询Student表的所有记录。
2 select * from student
3 Linq:
4     from s in Students
5     select s
6 Lambda:
7     Students.Select( s => s)

※按列查询

select sname,ssex,class from student 
3 Linq: 
4     from s in Students 
5     select new { 
6         s.SNAME, 
7         s.SSEX, 
8         s.CLASS
 9     }
 10 Lambda:
 11     Students.Select( s => new {
 12         SNAME = s.SNAME,SSEX = s.SSEX,CLASS = s.CLASS
 13     })

※distinct去重查询

 查询教师所有的单位即不重复的Depart列。
2 select distinct depart from teacher
3 Linq:
4     from t in Teachers.Distinct()
5     select t.DEPART
6 Lambda:
7     Teachers.Distinct().Select( t => t.DEPART)

※两个区间内查询

1 查询Score表中成绩在60到80之间的所有记录。
 2 select * from score where degree between 60 and 80
 3 Linq: 
 4     from s in Scores 
 5     where s.DEGREE >= 60 && s.DEGREE < 80
 6     select s 
 7 Lambda: 
 8     Scores.Where( 
 9         s => (
 10                 s.DEGREE >= 60 && s.DEGREE < 80
 11              )
 12     )

※在一个范围内查询

 select * from score where degree in (85,86,88)
 2 Linq:
 3     from s in Scores
 4     where (
 5             new decimal[]{85,86,88}
 6           ).Contains(s.DEGREE)
 7     select s
 8 Lambda:
 9     Scores.Where( s => new Decimal[] {85,86,88}.Contains(s.DEGREE))

※或关系查询

 查询Student表中"95031"班或性别为"女"的同学记录。
 2 select * from student where class =&#39;95031&#39; or ssex= N&#39;女&#39;
 3 Linq:
 4     from s in Students
 5     where s.CLASS == "95031"
 6        || s.CLASS == "女"
 7     select s
 8 Lambda:
 9     Students.Where(s => ( s.CLASS == "95031" || s.CLASS == "女"))

※排序

 以Class降序查询Student表的所有记录。
 2 select * from student order by Class DESC
 3 Linq:
 4     from s in Students
 5     orderby s.CLASS descending
 6     select s
 7 Lambda:
 8     Students.OrderByDescending(s => s.CLASS)

※行数查询

 select count(*) from student where class = &#39;95031&#39;
 2 Linq: 
 3     (    from s in Students 
 4         where s.CLASS == "95031"
 5         select s 
 6     ).Count() 
 7 Lambda: 
 8     Students.Where( s => s.CLASS == "95031" ) 
 9                 .Select( s => s)
 10                     .Count()

※平均值查询

 查询&#39;3-105&#39;号课程的平均分。
 2 select avg(degree) from score where cno = &#39;3-105&#39;
 3 Linq: 
 4     ( 
 5         from s in Scores 
 6         where s.CNO == "3-105"
 7         select s.DEGREE 
 8     ).Average() 
 9 Lambda:
 10     Scores.Where( s => s.CNO == "3-105")
 11             .Select( s => s.DEGREE)

※潜逃查询

查询Score表中的最高分的学生学号和课程号。
 2 select distinct s.Sno,c.Cno from student as s,course as c ,score as sc 
 3 where s.sno=(select sno from score where degree = (select max(degree) from score)) 
 4 and c.cno = (select cno from score where degree = (select max(degree) from score)) 
 5 Linq: 
 6     ( 
 7         from s in Students
 8         from c in Courses 
 9         from sc in Scores
 10         let maxDegree = (from sss in Scores
 11                         select sss.DEGREE
 12                         ).Max()
 13         let sno = (from ss in Scores
 14                 where ss.DEGREE == maxDegree
 15                 select ss.SNO).Single().ToString()
 16         let cno = (from ssss in Scores
 17                 where ssss.DEGREE == maxDegree
 18                 select ssss.CNO).Single().ToString()
 19         where s.SNO == sno && c.CNO == cno
 20         select new {
 21             s.SNO,
 22             c.CNO
 23         }
 24     ).Distinct()

※分组

 查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
 2 select avg(degree) from score where cno like &#39;3%&#39; group by Cno having count(*)>=5
 3 Linq: 
 4         from s in Scores 
 5         where s.CNO.StartsWith("3") 
 6         group s by s.CNO 
 7         into cc 
 8         where cc.Count() >= 5
 9         select cc.Average( c => c.DEGREE)
 10 Lambda:
 11     Scores.Where( s => s.CNO.StartsWith("3") )
 12             .GroupBy( s => s.CNO )
 13               .Where( cc => ( cc.Count() >= 5) )
 14                 .Select( cc => cc.Average( c => c.DEGREE) )
 15 Linq: SqlMethod
 16 like也可以这样写:
 17     s.CNO.StartsWith("3") or SqlMethods.Like(s.CNO,"%3")

※分组过滤

查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
 2 select avg(degree) from score where cno like &#39;3%&#39; group by Cno having count(*)>=5
 3 Linq: 
 4         from s in Scores 
 5         where s.CNO.StartsWith("3") 
 6         group s by s.CNO 
 7         into cc 
 8         where cc.Count() >= 5
 9         select cc.Average( c => c.DEGREE)
 10 Lambda:
 11     Scores.Where( s => s.CNO.StartsWith("3") )
 12             .GroupBy( s => s.CNO )
 13               .Where( cc => ( cc.Count() >= 5) )
 14                 .Select( cc => cc.Average( c => c.DEGREE) )
 15 Linq: SqlMethod
 16 like也可以这样写:
 17     s.CNO.StartsWith("3") or SqlMethods.Like(s.CNO,"%3")

※多表联合查询

 select sc.sno,c.cname,sc.degree from course as c,score as sc where c.cno = sc.cno
 2 Linq: 
 3     from c in Courses 
 4     join sc in Scores 
 5     on c.CNO equals sc.CNO
 6     select new 
 7     { 
 8         sc.SNO,c.CNAME,sc.DEGREE
 9     }
 10 Lambda:
 11     Courses.Join ( Scores, c => c.CNO,
 12                              sc => sc.CNO,
 13                              (c, sc) => new
 14                                         {
 15                                             SNO = sc.SNO,
 16                                             CNAME = c.CNAME,
 17                                             DEGREE = sc.DEGREE
 18                                         })
 19                 .Average()

 以上就是SQL、LINQ和Lambda表达式的内容,更多相关内容请关注PHP中文网(www.php.cn)!


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
​Unity遊戲開發:C#實現3D物理引擎與AI行為樹​Unity遊戲開發:C#實現3D物理引擎與AI行為樹May 16, 2025 pm 02:09 PM

在Unity中,3D物理引擎和AI行為樹可以通過C#實現。 1.使用Rigidbody組件和AddForce方法可以創建滾動的球。 2.通過行為樹節點如Patrol和ChasePlayer,可以設計AI角色巡邏和追擊玩家的行為。

u在c語言中是什麼意思 u在c語言中的無符號修飾u在c語言中是什麼意思 u在c語言中的無符號修飾May 16, 2025 pm 02:06 PM

u在C語言中用於聲明無符號整數常量。 1.u後綴表示無符號整數,如10u。 2.無符號整數範圍從0開始,不含負數,適用於大範圍正數和位操作。 3.使用無符號整數時需注意溢出和負數處理問題。

/0在c語言中是什麼意思? 空字符/0在字符串中的結尾/0在c語言中是什麼意思? 空字符/0在字符串中的結尾May 16, 2025 pm 02:03 PM

在C語言中,/0指的是空字符,用於標記字符串的結束。 1)空字符在ASCII碼表中的值是0。2)它是C語言字符串處理的基礎,編譯器會自動在字符串末尾添加空字符。 3)空字符不可見但在內存中存在,告訴字符串函數字符串結束位置。 4)使用時需確保字符串以空字符結尾,避免未定義行為。

c語言中bool表示什麼 bool類型在c語言中的真假值c語言中bool表示什麼 bool類型在c語言中的真假值May 16, 2025 pm 02:00 PM

在C語言中,bool類型是通過頭文件引入的,用於表示真假值。 1.bool類型的值可以是true(1)或false(0),任何非零值都被視為true。 2.使用bool類型可以提高代碼的可讀性,特別是在處理複雜的邏輯條件時。 3.雖然bool類型方便,但在某些情況下,使用整數類型進行布爾操作可能更高效。

在c語言中e的x次方怎麼弄 c語言中計算指數函數的方法在c語言中e的x次方怎麼弄 c語言中計算指數函數的方法May 16, 2025 pm 01:57 PM

在C語言中計算e的x次方可以使用泰勒級數法和標準庫中的exp函數。 1.泰勒級數法通過近似計算,適合精度要求不高的情況,但大數時可能溢出。 2.exp函數法使用math.h頭文件,精度高且優化好,但需鏈接數學庫。選擇方法需根據具體需求。

c語言中的avg是什麼意思 avg在c語言中的平均值縮寫c語言中的avg是什麼意思 avg在c語言中的平均值縮寫May 16, 2025 pm 01:54 PM

在C語言中,avg通常表示“平均值”,是計算一組數平均值的常見變量名。 1.聲明變量:用avg存儲平均值。 2.累加和計算:遍歷數據集並累加所有數值,然後除以數據集長度。 3.結果存儲:將平均值存入avg變量。使用double或float類型可提高計算精度。

aa在c語言中是什麼意思 aa在c語言中的變量命名規則aa在c語言中是什麼意思 aa在c語言中的變量命名規則May 16, 2025 pm 01:51 PM

"aa"在C語言中沒有特殊含義,僅為普通標識符。 1.變量名規則:只能包含字母、數字和下劃線,以字母或下劃線開頭,不能是關鍵字,區分大小寫。 2.最佳實踐:使用有意義的名稱,避免過長,使用駝峰或下劃線命名法,避免混淆名稱。

f在c語言中代表什麼 詳解c語言中f的含義及常見用法f在c語言中代表什麼 詳解c語言中f的含義及常見用法May 16, 2025 pm 01:48 PM

在C語言中,f代表浮點數,具體用法包括:1.作為格式說明符,用於printf和scanf函數;2.出現在數學函數名中,如sinf、cosf;3.作為浮點數後綴,指定類型為float;4.在浮點運算中需注意精度問題,使用容忍度進行比較;5.使用float可優化性能,但需權衡精度。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。