linq lanbda表达式的用法

1、 查询Student表中的所有记录的Sname、Ssex和Class列。
select 
sname,ssex,class from student
Linq:
    from s 
in Students
    select new {
        s.SNAME,
        
s.SSEX,
        s.CLASS
    }
Lambda:
    Students.Select( s => new {
        
SNAME = s.SNAME,SSEX = s.SSEX,CLASS = s.CLASS
    })

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

3、 
查询Student表的所有记录。
select * 
from student
Linq:
    from s in Students
    select s
Lambda:
    Students.Select( s => s)

4、 
查询Score表中成绩在60到80之间的所有记录。
select * 
from score where degree between 60 and 80
Linq:
    from s in Scores
    where s.DEGREE >= 
60 && s.DEGREE < 80
    select s
Lambda:
    Scores.Where( 
        s => 
(
                s.DEGREE >= 60 && s.DEGREE < 80

)
    )

5、 
查询Score表中成绩为85,86或88的记录。
select * 
from score where degree in (85,86,88)
Linq:
In
    from s in Scores
    where 
(
            new decimal[]{85,86,88}
          
).Contains(s.DEGREE)
    select s
Lambda:
    Scores.Where( s => new Decimal[] 
{85,86,88}.Contains(s.DEGREE))
Not 
in
    from s in Scores
    where !(
            new 
decimal[]{85,86,88}
          ).Contains(s.DEGREE)
    select 
s
Lambda:
    Scores.Where( s => 
!(new Decimal[]{85,86,88}.Contains(s.DEGREE)))

Any()应用:双表进行Any时,必须是主键为(String)
    CustomerDemographics 
CustomerTypeID(String)
    CustomerCustomerDemos (CustomerID 
CustomerTypeID) (String)
    一个主键与二个主建进行Any(或者是一对一关键进行Any)
    不可,以二个主键于与一个主键进行Any
    
    from e in 
CustomerDemographics
    where !e.CustomerCustomerDemos.Any()
    select 
e
    
    from c in Categories
    where !c.Products.Any()
    
select c

6、 
查询Student表中"95031"班或性别为"女"的同学记录。
select * 
from student where class =‘95031‘ or ssex= N‘女‘
Linq:
    
from s in Students
    where s.CLASS == "95031" 
       || s.CLASS == 
"女"
    select s
Lambda:
    
Students.Where(s => ( s.CLASS == "95031" || s.CLASS == "女"))

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

8、 
以Cno升序、Degree降序查询Score表的所有记录。
select * 
from score order by Cno ASC,Degree DESC
Linq:(这里Cno ASC在linq中要写在最外面)
    from s in Scores
    orderby 
s.DEGREE descending
    orderby s.CNO ascending 
    select 
s
Lambda:
    
Scores.OrderByDescending( s => s.DEGREE)
          .OrderBy( s => 
s.CNO)

9、 
查询"95031"班的学生人数。
select 
count(*) from student where class = ‘95031‘
Linq:
    (    from s in Students
        where 
s.CLASS == "95031"
        select s
    ).Count()
Lambda:
    Students.Where( s => s.CLASS == "95031" 
)
                .Select( s => s)
                    .Count()

10、查询Score表中的最高分的学生学号和课程号。
select 
distinct s.Sno,c.Cno from student as s,course as c ,score as sc 
where 
s.sno=(select sno from score where degree = (select max(degree) from
score))
and c.cno = (select cno from score where degree = (select max(degree) 
from score))
Linq:
    (
        
from s in Students
        from c in Courses
        from sc in 
Scores
        let maxDegree = (from sss in Scores
                        
select sss.DEGREE
                        ).Max()
        let sno = (from 
ss in Scores
                where ss.DEGREE == maxDegree
                
select ss.SNO).Single().ToString()
        let cno = (from ssss in 
Scores
                where ssss.DEGREE == maxDegree
                
select ssss.CNO).Single().ToString()
        where s.SNO == sno && 
c.CNO == cno
        select new {
            s.SNO,
            
c.CNO
        }
    ).Distinct()
操作时问题?执行时报错: where s.SNO == sno(这行报出来的) 运算符"=="无法应用于"string"和"System.Linq.IQueryable<string>"类型的操作数
解决:
原:let 
sno = (from ss in Scores
                where ss.DEGREE == 
maxDegree
                select 
ss.SNO).ToString()
Queryable().Single()返回序列的唯一元素;如果该序列并非恰好包含一个元素,则会引发异常。 
解:let 
sno = (from ss in Scores
                where ss.DEGREE == 
maxDegree
                select 
ss.SNO).Single().ToString()

11、查询‘3-105‘号课程的平均分。
select 
avg(degree) from score where cno = ‘3-105‘
Linq:
    (
        from s in Scores
        
where s.CNO == "3-105"
        select s.DEGREE
    
).Average()
Lambda:
    Scores.Where( 
s => s.CNO == "3-105")
            .Select( s => 
s.DEGREE)
                .Average()

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

13、查询最低分大于70,最高分小于90的Sno列。
select sno 
from score group by sno having min(degree) > 70 and max(degree) < 
90
Linq:
    from s in Scores
    
group s by s.SNO
    into ss
    where ss.Min(cc => cc.DEGREE) > 70 
&& ss.Max( cc => cc.DEGREE) < 90
    select new
    
{
        sno = ss.Key
    }
Lambda:
    Scores.GroupBy (s => 
s.SNO)
               .Where (ss => ((ss.Min (cc => cc.DEGREE) > 70) 
&& (ss.Max (cc => cc.DEGREE) < 90)))
                   .Select 
( ss => new {
                                        sno = 
ss.Key
                                     })

14、查询所有学生的Sname、Cno和Degree列。
select 
s.sname,sc.cno,sc.degree from student as s,score as sc where s.sno =
sc.sno
Linq:
    from s in 
Students
    join sc in Scores
    on s.SNO equals sc.SNO
    select 
new
    {
        s.SNAME,
        sc.CNO,
        sc.DEGREE
    
}
Lambda:
    Students.Join(Scores, s 
=> s.SNO,
                          sc => sc.SNO,

(s,sc) => 
new{
                                            SNAME = 
s.SNAME,
                                            CNO = 
sc.CNO,
                                            DEGREE = 
sc.DEGREE
                                          })

15、查询所有学生的Sno、Cname和Degree列。
select 
sc.sno,c.cname,sc.degree from course as c,score as sc where c.cno = 
sc.cno
Linq:
    from c in 
Courses
    join sc in Scores
    on c.CNO equals sc.CNO
    select 
new
    {
        sc.SNO,c.CNAME,sc.DEGREE
    }
Lambda:
    Courses.Join ( Scores, c => c.CNO,

sc => sc.CNO,

(c, sc) => new

{
                                            SNO = sc.SNO,

CNAME = c.CNAME,

DEGREE = 
sc.DEGREE
                                        })

16、查询所有学生的Sname、Cname和Degree列。
select 
s.sname,c.cname,sc.degree from student as s,course as c,score as sc where s.sno 
= sc.sno and c.cno = sc.cno
Linq:
    
from s in Students
    from c in Courses
    from sc in Scores
    
where s.SNO == sc.SNO && c.CNO == sc.CNO
    select new { 
s.SNAME,c.CNAME,sc.DEGREE }

时间: 2024-08-08 17:45:48

linq lanbda表达式的用法的相关文章

Linq中Lanbda表达式做参数

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lanbda表达式做参数 { class Program { static void Main(string[] args) { int[] Array = new int[] { 3, 2, 4, 56, 6, 14, 53 }; Func<int, bool> mtDelB = delegate(in

.NET深入解析LINQ框架(六:LINQ执行表达式)

阅读目录: 1.LINQ执行表达式 在看本篇文章之前我假设您已经具备我之前分析的一些原理知识,因为这章所要讲的内容是建立在之前的一系列知识点之上的,为了保证您的阅读顺利建议您先阅读本人的LINQ系列文章的前几篇或者您已经具备比较深入的LINQ原理知识体系,防止耽误您的宝贵时间. 到目前为止我们对LINQ的执行原理已经很清楚了,从它的前期构想到它真正为我们所用都有足够的证据,但是似乎问题并没有我们想的那么简单,问题总是在我们使用中频频出现尤其是新技术的使用,当然有问题才能有进步. 一:LINQ执行

LINQ查询表达式---------let子句

LINQ查询表达式---------let子句 let子句创建一个范围变量来存储结果,变量被创建后,不能修改或把其他表达式的结果重新赋值给它.此范围变量可以再后续的LINQ子句中使用. class Program { static void Main(string[] args) { int[] number = { 12, 15, 16, 17, 18, 19, 20 }; var query = from num in number let n = num % 2 where n == 0

LINQ查询表达式(1) - 查询表达式基础

什么是查询?它有什么用途? "查询"是指一组指令,这些指令描述要从一个或多个给定数据源检索的数据以及返回的数据应该使用的格式和组织形式. 查询不同于它所产生的结果.通常,源数据会在逻辑上组织为相同种类的元素序列. SQL 数据库表包含一个行序列. 与此类似,ADO.NET DataTable 包含一个 DataRow 对象序列. 在 XML 文件中,有一个 XML 元素"序列"(不过这些元素按分层形式组织为树结构). 内存中的集合包含一个对象序列.从应用程序的角度来

LinQ Lambda表达式用作泛型活动

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.IO; namespace LambdaExpressionAction { class Program { static void Main(string[] args) { //Action:泛型委托,可以将行为捕获为一个可调用的对象 //只需要

Linq专题之创建Linq查询表达式

本节我们主要介绍一下如何创建查询集合类型,关系数据库类型,DataSet对象类型和XML类型的数据源的Linq查询表达式. 下面在实例代码ReadyCollectionData()函数创建了准备的数据源: 1.创建集合类型的查询. 创建一个UserBaseInfo类: 1 public class UserBaseInfo 2 { 3 private List<string> aliasname; 4 private int id; 5 private string email; 6 priv

C# 两个集合比较差值 Linq的Except的用法

C# 两个集合比较差值 Linq的Except的用法 值类型的集合比较差值 List<string> strList1 = new List<string>(){"a", "b", "c", "d"}; List<string> strList2 = new List<string>() { "a", "b", "f",

python lambda表达式简单用法【转】

python lambda表达式简单用法 1.lambda是什么? 看个例子: g = lambda x:x+1 看一下执行的结果: g(1) >>>2 g(2) >>>3 当然,你也可以这样使用: lambda x:x+1(1) >>>2 可以这样认为,lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体,用函数来表示为: 1 def g(x):2 return x+1 非常容易理解,在这里lambda简化了函数定义

Linq 中 Join 的用法

Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下. 注:本文内容主要来自<Linq实战>,本例中用到的对象请见文章底部. 1. 组连接 组连接是与分组查询是一样的.即根据分组得到结果. 如下例,根据publisther分组得到结果. 使用组连接的查询语句如下: //使用组连接            var GroupQuery = from publisher in SampleData.Publishers                             jo