谜一样的LINQ查询

LINQ查询

一、LINQ概念

1.引入LINQ(.NET存在的问题)

(1)嵌入方式开发嵌入SQL语句,语句有任何提示,容易出错
(2)编程语言数据类型与SQL类型完全两套体系
(3)SQL和XML都有格子查询语言,二面相对象没有自己的查询语言

2.LINQ(Language Integrated Query) 语言集成查询

(1)将查询功能直接引入到C#,VB,.NET等编程语言中
(2)查询操作可通过编程语言自身来完成,而不是嵌入字符串SQL语句

二、LINQ组成

在这里插入图片描述

1.LINQ to Objects 主要负责对象的查询
2.LINQ to XML 负责XML查询
3.LINQ to ADO.NET 数据库的查询
(1)LINQ to SQL 无人用
(2)LINQ to DataSet 数据集
(3)LINQ to Entities 实体

三、LINQ查询原理

Created with Raphaël 2.2.0 截取数据源 定义查询 执行查询

四、LINQ查询的两种形式

1.查询方法方式(Method Syntax)

利用System.Linq.Enumerable类中扩展方法Lambda表达方式

2.查询语句方法(Query Syntax)

更接近SQL语法查询方式,可读性较好,查询语句最终被翻译成成查询方法

3.两中形式比较

(1)CLR本身不理解查询语句,只理解查询方法
(2)编译只编译查询语句翻译查询方法
(3)部分查询方法目前没有对应的语句.如:Count()和Max()
一般情况建议使用可读性较强的查询语句

五、查询方法

1.获取数据方法:

扩展方法:Select()
参数:委托实例(委托实例是一个方法)

using System.Linq;//引入LINQ命名空间自动引入
	int[] num = { 1, 2, 3, 4, 5, 6, 7, 8 };
	var list = num.Select(item => item * 2);
    foreach (var item in list)
            {
                Console.Write(item+" ");
            }
      Console.ReadLine();

注意:
select()方法括号中是一个Lambda表达式
返回结果是一个迭代[隐藏循环]器(Iterator)
不论数组还是集合都可以使用select()方法
执行结果:
在这里插入图片描述

2.筛选数据方法:

扩展方法:where()
参数:判断条件

	int[] num = { 1, 2, 3, 4, 5, 6, 7, 8 };
	var list = num.Where(item => item % 2 != 0);
    foreach (var item in list)
    {
        Console.Write(" "+item);
     }
     Console.ReadLine();

执行结果:
在这里插入图片描述

3.排序数据方法:

扩展方法:OrderBy()
默认按照升序(Lambda表达式)
降序方法OrderByDescending()

	int[] num = { 1, 2, 3, 4, 5, 6, 7, 8 };
	var list = num.Select(item => item).OrderBy(item => item);
    foreach (var item in list)
    {
       Console.Write(" "+item );
    }
    Console.ReadLine();

执行结果:
在这里插入图片描述

降序排序

	int[] num = { 1, 2, 3, 4, 5, 6, 7, 8 };
	var list = num.Select(item => item).OrderByDescending(item => item);
   	foreach (var item in list)
    {
      Console.Write(" "+item);
    }
    Console.ReadLine();

执行结果:
在这里插入图片描述

4.分组数据方法:

扩展方法:GroupBy()
参数:一个分组字段

	string[] numbers = {"11","12","13","14","15","16","17","18","21","22","23","24","25","26","31","32" };
    var list = numbers.Select(item => item).GroupBy(item => item.Substring(0, 1));
    foreach (var item in list)
    {
      Console.WriteLine("分组字段:"+item.Key);
       foreach (var i in item)
       {
           Console.WriteLine(i);
        }
    }
    Console.ReadLine();

执行结果:
在这里插入图片描述

六、查询语句

1.查询表达式

是一种用查询语法表示的表达式,由一组类似于SQL的语法编写的句子组成
每一个子句可以包含一个或多个C#表达式

	int[] numbers = { 5, 26, 12, 7, 8, 33, 6, 3, 10 };
     var list = from item in numbers where item % 2 != 0 orderby item * 2 descending select item*2;
     foreach (var item in list)
      {
            Console.Write(" "+item); //  66 14 10 6
      }
     Console.ReadLine();

LINQ查询表达式必须以from子句开头,并且必须以select或者group子句结束,中间可以添加多个子句

	string[] name = { "李明", "李红", "李白", "张三", "张无忌", "张晓明", "王大锤", "王二牛", "赵小果", "赵冕" };
     var list = from item in name group item by item.Substring(0, 1);
     foreach (var item in list)
     {
         Console.WriteLine("分组字段为:"+item.Key);
         foreach (var i in item)
         {
             Console.WriteLine(i);
         }
    }
    Console.ReadLine();

执行结果:
在这里插入图片描述

2.查询子句

(1)from子句:指定查询操作的数据源范围变量
(2)where子句:筛选元素的逻辑条件,返回值必须是一个bool类型
(3)select子句:指定查询结果的类型表现形式
(4)orderby子句:对查询结果进行排序(升序或降序)
(5)group… by…子句:对查询结果进行分组
(6)into子句:提供一个临时标识符,该表示可以充当对join、group、select子句结果的引用
(7)join子句:连接多个查询操作的数据源
(8)let子句:引入用于存储查询表达式中的子表达式结果的范围变量

2.1from子句

数据源
(1)如果数据源是泛型类型,则编译器可以自动推断出范围变量的类型
(2)如果数据源是非泛型类型,如ArrayList,则必须显示的指定范围变量的数据类型
以下为非泛型类型

	ArrayList nums = new ArrayList(); //创建动态数组
    nums.AddRange(new int[] {1,5,3,7,8,6,9,12 }); //数据源
    var list = from int item in nums where item % 2 != 0 orderby item * 2 descending select item * 2; 
    //需要声明int类型的元素,item表示数据源中的每一个元素
   foreach (var item in list)
   {
       Console.WriteLine(item);
    }
    Console.ReadLine();

执行结果:

在这里插入图片描述

2.2from复合子句查询

Student类

public class Student
    {
        /// <summary>
        /// 学号
        /// </summary>
        public int StuId { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string StuName { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int StuAge { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public string StuSex { get; set; }
        /// <summary>
        /// 成绩
        /// </summary>
        public List<int> StuScore { get; set; }
    }

创建对象

Student stu1 = new Student() { StuId = 1001, StuName = "王华", StuSex = "男", StuAge = 21, StuScore = new List<int>() { 65, 86, 48 } };
Student stu2 = new Student() { StuId = 1002, StuName = "李明", StuSex = "男", StuAge = 21, StuScore = new List<int>() { 75, 68, 75 } };
Student stu3 = new Student() { StuId = 1003, StuName = "李红", StuSex = "女", StuAge = 19, StuScore = new List<int>() { 75, 69, 86 } };
Student stu4 = new Student() { StuId = 1004, StuName = "胡小燕", StuSex = "女", StuAge = 22, StuScore = new List<int>() { 86, 78, 89 } };
Student stu5 = new Student() { StuId = 1005, StuName = "牛大锤", StuSex = "男",StuAge=23, StuScore = new List<int>() { 66, 78, 78 } };
Student stu6 = new Student() { StuId = 1004, StuName = "马大哈", StuSex = "女", StuAge = 16, StuScore = new List<int>() { 56, 68, 59 } };
Student stu7 = new Student() { StuId = 1005, StuName = "赵泽", StuSex = "男",StuAge=21, StuScore = new List<int>() { 76, 58, 68 } };

存入集合中

 List<Student> stulist1 = new List<Student>(){ stu1,stu2,stu3};
 List<Student> stulist2 = new List<Student>() { stu4, stu5, stu6, stu7 };
 List<Student> stulist3 = new List<Student>() { stu1,stu2,stu3, stu4, stu5, stu6, stu7 };

查询成绩中有一门成绩超过80分的学生

	var list = from item in stulist1 from score in item.StuScore where score>80 select item;
    foreach (var item in list)
    {
        Console.WriteLine(item.StuName);
     }
    Console.ReadLine();

执行结果:
在这里插入图片描述

2.3from多个子句查询

查询出所有年龄大于20岁的学生

	var res = from item1 in stulist1 where item1.StuAge > 20  
				from item2 in stulist2 where item2.StuAge > 20 
				select new { item1, item2 };
    foreach (var item in res)
    {
      Console.WriteLine("年龄大于20的学生有:{0}",item.item1.StuName);
      //另一种写法:Console.WriteLine($"年龄大于20岁的学生有:{item.item1.StuName}");
      Console.WriteLine($"年龄大于20岁的学生有:{item.item2.StuName}");
    }
    Console.ReadLine();
发布了137 篇原创文章 · 获赞 185 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dust__/article/details/104998839