查询表达式是一种查询语法表示的表达式,由一组用类似SQL的语法编写的句子组成。每一个子句可以包含一个或多个C#表达式。
var list = from num in nums where num % 2 != 0 orderby num descending select num;
LINQ查询表达式必需以
from
子句开头,并且必需以select
或group
子句结束,中间可以添加多个子句
from
子句:指定查询操作的数据源和范围变量where
子句:筛选元素的逻辑条件,返回值是一个bool
类型select
子句:指定查询结果的类型和表现形式orderby
子句:对查询结果进行排序(升序或降序)group
子句:对查询结果进行分组into
子句:提供一个临时的标识符,该表示可充当对join/group/select
子句结果的引用join
子句:连接多个查询操作的数据源let
子句:引入用于存储查询表达式的子表达式结果的范围变量from
子句LINQ查询表达式必需包含from
子句,并且必须以from
子句开头。from
子句指定的数据源类型必须为IEnumerable
、IEnumerable<T>
或者两者的派生类型(例如:数据、List
int[] nums = {1, 7, 9, 10, 29, 21} var list = from num in nums where num % 2 != 0 orderby num descending select num;
如果数据源是泛型类型,则编译器可以自动推断出范围变量的类型,比如上面的num
类型为int
类型。如果数据源是非泛型类型,如ArrayList
,则必须显式的指定范围变量的数据类型。
from
子句查询如果数据源(本身是一个序列)的元素还包含子数据源(如序列、列表等),如果要查询子数据源中的数据则需要使用from
子句。
Student obj1 = new Student() { StudId = 1001, StuName = "学员1", ScoreList = new List<int>() { 90, 80, 100 } }; Student obj2 = new Student() { StudId = 1001, StuName = "学员2", ScoreList = new List<int>() { 90, 98, 50 } }; Student obj3 = new Student() { StudId = 1001, StuName = "学员3", ScoreList = new List<int>() { 90, 60, 45 } }; List<Student> stuList = new List<Student>() { obj1, obj2, obj3 }; // 查询成绩包含95分以上的学员 var result = from stu in stuList from score in stu.ScoreList where score >= 95 select stu; // 显示查询结果 foreach (var item in result) { Console.WriteLine("成绩包含95以上的学员有:{0}", item.StuName); } Console.ReadLine();
输出结果:
成绩包含95以上的学员有:学员1 成绩包含95以上的学员有:学员2