SQL, LINQ 및 Lambda 표현식

黄舟
풀어 주다: 2017-02-23 10:05:34
원래의
1452명이 탐색했습니다.

간단한 소개

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 표준 쿼리 연산자를 구현합니다. 전달, 탐색, 정렬, 쿼리, 조인, 합계, 최대값, 최소값 및 기타 작업과 같은 작업이 포함됩니다.
람다 식은 실제로 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     })
로그인 후 복사
로그인 후 복사

※고유 중복제거 조회

 查询教师所有的单位即不重复的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)
로그인 후 복사

※2개의 조회 간격 내

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)!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!