• linq学习


    本篇文章主要介绍linq的基本用法,采用sql和linq比较的方式由浅入深进行学习,
    注意:此文章是根据真实表来进行案例说明,表结构如下:
     表1:    Student(学生表)                    
    字段: Student_Id(学生ID)                        
                   Student_Name(学生姓名)                   
                   Student_age(年龄)                              
                   Student_Sex(性别)                                            
            Student_Phone(手机号可为Null)             
    表2: Book(图书借阅管理表)
     Book_Id(图书借阅ID)
         Book_Name(书名)
    Book_StudentId(借阅者ID)
    Book_Date(借阅日期)
    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
                                    };

  • 相关阅读:
    RHEL6.x 删除Oracle11g
    通过IPV6上QQ及自建IPV6代理的方法
    Carrier frequency and EARFCN
    FDD LTE frequency band allocations
    Cmake参考资料
    sigal & mq_notify
    哈夫曼编码与解码
    哈夫曼数与哈夫曼编码
    算法做题顺序
    我的大学
  • 原文地址:https://www.cnblogs.com/lgx5/p/5824133.html
Copyright © 2020-2023  润新知