C#总结三linq

linq学习总结

LINQ查询语法:

①方法语法:扩展方法 + lambda表达式; 
②声明式的查询语法类似于SQL查询方式。 
PS:什么是扩展方法?扩展方法就是向现有的类型添加一些方法,使得该类型在功能上有所扩展!扩展方法可以简化以继承实现的方法扩展,并且在不知道原有基类的内部构造时,将十分有利。 
a.方法语法(传输链):

IEnumerabl<T>query=源集合.Where(过滤,必须bool表达式).OrderBy(排序条件).Select(选择条件)

b.查询表达式:

var 结果集 = from n in 数据源  wher 过滤表达式 orderby 排序 select 投影(选择)
查询表达式需以
select或者group结束!
lambda表达式是对匿名方法的简化,任何匿名方法使用的场合lambda表达式都可以替代,并且代码更加简洁。lambda表达式会广泛用于LINQ中。lambda表达式的形式如下: 
*①无参的:()=>{处理语句}; 
②一个参数的:参数=>{处理语句}; 
③多个参数的:(参数1,参数2,…参数n)=>{处理语句}。 
备注:一条处理语句,{}可以省略! 

 

 

查询出所有的学生记录

Sql:Select * from Student

Linq:IQueryable<Student> studentlq =from studentE in D.Student select student

 

查询出年龄大于18并且性别为男,有手机的学生

Sql: Select * from Student where Student_age>18 and Student_sex=’男’ and Student_Phone is not null

LINQ:(方法1,直接查询)

IQueryable<Student> studentlq =from studentE in D.Student select student where

student.student_age>18 && student.Student_sex=’男’ && student. Student_Phone.HasVlaue

LINQ:(方法2,执行二次查询,这里直接使用Lambda表达式)

IQueryable<Student> studentlq = from studentE in D.Student select student;

Studentlq= studentlq.where(w=>w. studentlq&& student.Student_sex=’男’ && student. Student_Phone.HasVlaue);

 

解析:SQL中的AND和OR分别对应LINQ中的&&和||
        SQL中的is not null 和 is null 分别对应: 字段名.HasValue 和 !字段名.HasValue

 

查询出年龄大于18,或者性别为女生的学生,并按年龄排序

Sql:select * from student where student_age>=18 or student_sex=’女’ order by student_age desc

Linq:

方法1:

IQueryable<Student> StudentLq = from StudentE in D. Student
                       where StudentE. Student_age >= 18 || StudentE. Student_Sex == ‘女’ 
                       orderby StudentE. Student_age descending
                       select StudentE;

解析:SQL中的ASC和DESC分别对应LINQ中的ascending 和 descending
如果先对年龄进行升序,在对学生ID进行降序,那么代码如下:orderby StudentE. Student_age ascending,orderby StudentE. Student_Id descending

方法2:

IQueryable<Student> StudentLq = from StudentE in D. Student select StudentE;
StudentLq=StudentLq.Where(W => W.Student_age >= 18 ||W. Student_Sex == ‘女’);
StudentLq=StudentLq.OrderByDescending(W => W.Student_age);解析:先对某个字段进行升序使用OrderBy()方法,降序使用OrderByDescending()方法再对某个字段进行升序使用ThenBy()方法,降序使用ThenByDescending()方法
 如果先对年龄进行升序,在对学生ID进行降序,那么代码如下:
StudentLq=StudentLq.OrderBy(W => W.Student_age).ThenByDescending(W => W.Student_Id);

 

四:根据条件查询并计算值(查询出年龄小于18的学生个数)
SQL: select count(*) from Student where Student_age < 18
注意:count(*)统计总记录数 可以count(字段名) 统计某个字段的记录数
avg():计算平均值 max():计算最大值 min():计算最小值 sum():求和计算
LINQ: int ageCount = (from StudentE in D. Student
                     where StudentE. Student_age < 18 
                     select StudentE.Count();
解释:上面的写法等同于下面方法:
      int ageCount =D. Student.Count(StudentE => StudentE.Student_age < 18)
如果对某一个字段进行求个数的话,直接在取值的时候取出这个字段,然后求个数,如下:
例如:求2013年至今一共借出多少本书
SQL:select sum(Book_Amount) from Book where Book_Date > '2013-01-01'
LINQ:int bookCount = (from BookE in D. Book where BookE. Book_Date > DateTime.Parse('2013-01-01')
select BookE.Sum();
注:Count():求个数 Average():求平均 Min():求最小值 Max():求最大值,方法同Sum()的方法

 

五:IN操作(查询书名为"中国","母亲","散文"的记录)
SQL: select * from Book where Book_Name in ('中国','母亲','散文')
LINQ: string[] name = { "中国", "母亲", "散文"};
IQueryable<Book> BookLq= from BookE in D.Book
                   where name.Contains(BookE.Book_Name)
                   select BookE;

 

六:LIKE操作(查询书名中包括"中国"两字的记录)
SQL: select * from Book where Book_Name like  '%中国%'
LINQ: IQueryable<Book> BookLq= from BookE in D.Book
                 where BookE.Book_Name.Contains("中国")
                 select BookE;
解释:EndsWith("中国"):以中国这两个字符结尾的书名 StartsWith(中国"):以中国这两个字符开始的书名
LIKE操作也可以使用一下方法:
           IQueryable<Book> BookLq= from BookE in D.Book
            where SqlMethods.Like(BookE.Book_Name, "%中国%")
            select BookE;

 

查询并且筛选掉重复值(查询2013年至今哪些书被借出去过)
SQL:select distinct Book_Name from Book where Book_Date > '2013-01-01'
LINQ: IQueryable<String> bookString = (from BookE in D. Book
                  where BookE. Book_Date > DateTime.Parse('2013-01-01')
                  select BookE.Book_Name).Distinct();

 

分组查询(查询哪些客户分别借了多少本书)
SQL:select Book_StudentId,sum(Book_Amount) from Book  group by Book_StudentId
      LINQ:IQueryable<Book> BookLq =from BookE in D.Book
                      group BookE by BookE.Book_StudentId into NesBook
                      orderby NesBook.Sum(W=> W.Book_Amount) descending //排序
    select new {BookStudentId =NesBook.Key,
    BookAmount= NesBook.Sum(W=> W.Book_Amount)
    }; 
解释:这只是根据哪个客户来分组的,如果根据客户和书名2个字段来分组,可以使用下面的代码:
 IQueryable<Book> BookLq =from BookE in D.Book
              group BookE by new {BookE.Book_StudentId,BookE.Book_Name}
 into NesBook orderby NesBook.Sum(W=> W.Book_Amount) descending //排序
 select new {BookStudentId =NesBook.Key.Book_StudentId,
       BookName =NesBook.Key.Book_Name,
    BookAmount= NesBook.Sum(W=> W.Book_Amount) }; 
 
   以下介绍内连接和外连接,这个时候我们先声明一个实体对象,方便我们实例的赋值!
 public class NEW_LIST
           {
        public string Student_Name_List { get; set; }//学生姓名
        public int Student_age_List { get; set; }//学生年龄
        public string Book_Name_List { get; set; }//书名
        public DateTime Book_Date_List { get; set; }//借阅日期
        public int Book_Amount_List { get; set; } //借阅数据的个数
               .......想要更多字段的可以在这里添加,我就不一 一写上了
    }

 

九 :内连接(jion和inner jion)
jion和inner jion 用法一样 都是表中存在至少一个匹配时,返回行,也就是说当2个表中拥有相同关联记录的时候才返回行
我们来看下面的例子:取出2013年至今哪些学生借阅过哪些书籍[图书表里面有某一个学生,学生表里面没有的将不被查出]
SQL:SELECT Student.Student_Name, Student.Student_age, Book.Book_Name, 
 Book.Book_Date,Book.Book_Amount FROM Book INNER JOIN Student
ON Book.Book_StudentId=Student.Student_Id 
 where Book.Book_Date > '2013-01-01' order by Student.Student_Name desc
 Linq:IQueryable<NEW_LIST> newLq =  from bookE in D.Book
    join StudentE in D.Student on bookE.Book_StudentId equals StudentE.Student_Id  where bookE.Book_Date > '2013-01-01'
 orderby StudentE.Student_Name descending
                select new NEW_LIST{
                       Student_Name_List = StudentE.Student_Name,
                       Student_age_List = StudentE.Student_age,
                       Book_Name_List = bookE.Book_Name,
                       Book_Date_List = bookE.Book_Date,
                       Book_Amount_List = bookE.Book_Amount
                   };


十 :外连接(left jion和right jion)
LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行也就是说从左表1(主表)那里返回所有的行,即使在右表 (表2) 中没有匹配的行也照样查出记录
RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行也就是说从右表 (表2[主表]) 那里返回所有的行,即使在左表 (表1) 中没有匹配的行
       LEFT JOIN 和 RIGHT JOIN用法一样,主要是看把那个表作为主表查询出来
       我们来看下面的例子:
   取出2013年至今哪些书籍被学生借阅过[图书表里面有某一个学生,学生表里面没有的也将查询出图书记录]
SQL:SELECT Student.Student_Name, Student.Student_age, Book.Book_Name, 
                Book.Book_Date,Book.Book_Amount FROM Book LEFT JOIN Student
       ON Book.Book_StudentId=Student.Student_Id 
                where Book.Book_Date > '2013-01-01' order by Student.Student_Name desc
Linq:IQueryable<NEW_LIST> newLq =  from bookE in D.Book  
join StudentE in D.Student
         on bookE.Book_StudentId equals StudentE.Student_Id
         into newsBook from NbooE in newsBook.DefaultIfEmpty()
   select new NEW_LIST{
        Student_Name_List=NbooE.Student_Name==null?"":NbooE.Student_Name,
        Student_age_List = NbooE.Student_age==null?"":NbooE.Student_age,
        Book_Name_List = bookE.Book_Name,
        Book_Date_List = bookE.Book_Date,
                             Book_Amount_List = bookE.Book_Amount
                                };

 

 

猜你喜欢

转载自blog.csdn.net/u010773333/article/details/81067598