查询表达式的结构
结构要求:form子句和select…group子句必须有 其他子句可以没有
语法
from Type item in items
Type是集合中元素的类型,可有可无,编辑器会根据集合推断类型
items是可枚举的集合(不是枚举类型)
item是迭代变量的名字,迭代变量逐个表示集合中的元素
例子
int[] nums = new[] { 1, 2, 3 };
IEnumerable<int> result = from int num in nums
where num < 2
select num;
join子句(联结)
作用:将多个集合的数据结合
语法:join 迭代变量名 in 集合 on (集合1的字段 equals 集合2的字段)
字段用于联系两个集合 字段相等的元素可以结合
联结操作接受两个集合,创建一个临时的对象集合,
新集合中的元素包含集合1和集合2元素的字段
例子
Student类中包含学号id、姓名name
StudentClass类中包含学号id、课程course
Student数组 students;
id | name |
---|---|
1 | 小红 |
2 | 小白 |
StudentClass数组 studentClasses
id | course |
---|---|
1 | 数学 |
2 | 语文 |
2 | 数学 |
3 | 英语 |
var joinS= from s in students join c in sutdentClasses on s.id equals c.id
根据学号id联结这两个集合,学号相同的对象结合在一起组成新的集合
新集合中的元素
id | name | course |
---|---|---|
1 | 小红 | 数学 |
2 | 小白 | 语文 |
2 | 小白 | 数学 |