本篇文章主要介绍linq的基本用法,采用sql和linq比较的方式由浅入深进行学习,

注意:此文章是根据真实表来进行案例说明,表结构如下:
 表1:    Student(学生表)                      表2: Book(图书借阅管理表)

字段: Student_Id(学生ID)                             Book_Id(图书借阅ID)

Student_Name(学生姓名)                      Book_Name(书名)

Student_age(年龄)                                Book_StudentId(借阅者ID)

Student_Sex(性别)                                Book_Date(借阅日期)

Student_Phone(手机号可为Null)            Book_Amount(借阅本数)

首先在MODEL层建立一个LINQ to
SQL类,取名为:Assemble.dbml,将表1和表2拖入到文件中形成

表结构对象(实体)。

在使用的时候使用AssembleDataContext D = new AssembleDataContext ();

注意以后D变量不再强调声明。

一: 查询出所有的学生记录

SQL: select * from Student

LINQ: IQueryable<Student> StudentLq = from StudentE in D. Student select StudentE;

二:根据条件进行查询(查询出年龄大于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

       where
StudentE. Student_age >= 18 && StudentE. Student_Sex == ‘男’

       && StudentE. Student_Phone.HasValue

       select
StudentE;

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

    IQueryable<Student> StudentLq = from StudentE in D. Student select StudentE;

                StudentLq=StudentLq.Where(W => W.Student_age >= 18 &&

W. Student_Sex == ‘男’ && W. Student_Phone.HasValue);

解析:SQL中的AND和OR分别对应LINQ中的&&和||

SQL中的is not null 和 is null 分别对应: 字段名.HasValue 和 !字段名.HasValue

  如果只是根据ID或者某一条件查询出结果有且只有1条记录的话可以使用下面的LINQ语句

    Student StudentLq = D.Student.Single(W => W.Student_Id == 1);

上面语句如果数据库中无记录或者有多条记录,会报错!

三:根据条件查询并排序(查询出年龄大于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

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

     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.Book_Amount).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
                                };

十一:分页查询(查询2013年至今所借的图书信息,以及借阅者是谁,只查询出第1到第10条记录)

SQL:   select * from (select row_number() over (order by Book_Date desc) as cid,
            (select Student_Name from Student where Student_Id=Book_StudentId) as newBook_StudentName,
            Book_Id,Book_Name,Book_Date,Book_Amount

from Book where Book_Date > '2013-01-01' ) NewBook

where NewBook.cid between 1 and 10 order by Book_Date desc

LINQ:

后续持续更新。。。

最新文章

  1. [转]Web APi之认证(Authentication)及授权(Authorization)【一】(十二)
  2. Python-第三方库requests详解
  3. Flask 重新认识
  4. ubuntu16.04 NVIDIA显卡驱动安装
  5. “LC.exe”已退出,代码为 -1
  6. include a image in devexpress datagrid
  7. 使用 system.io.filesysteminfo 来查找文件。
  8. Linux 中 java 访问 windows共享目录
  9. MySQL 高效查询
  10. ecshop商城_
  11. java 线程方法 ---- join()
  12. 初学git
  13. taro refs引用
  14. Java Script 基础总结
  15. 大型运输行业实战_day15_1_全文检索之Lucene
  16. 全网最详细的CentOS7里如何安装MySQL(得改为替换安装MariaDB)(图文详解)
  17. 【laravel5.4】Baum无限极分类和collect助手函数、transform()中间件(转换数据)方法使用
  18. jquery获取父级元素、子级元素、兄弟元素的方法
  19. SpringData_PagingAndSortingRepository接口
  20. Unity Lighting - High Dynamic Range (HDR) 高动态范围(五)

热门文章

  1. eclipse安装插件:
  2. mysql5.6与mysql5.5不同
  3. ASP.NET网站使用Kindeditor富文本编辑器配置步骤
  4. Linux之FTP服务
  5. vue.js 源代码学习笔记 ----- 工具方法 env
  6. zookeeper的c API 单线程与多线程问题 cli_st和cli_mt
  7. Data truncated for column
  8. VMWare的共享文件的安装指南
  9. [置顶] Android AOP 实践笔记
  10. HAWQ + MADlib 玩转数据挖掘之(五)——奇异值分解实现推荐算法