SelectMany操作符提供了将多个from子句组合起来的功能,相当于数据库中的多表连接查询,它将每个对象的结果合并成单个序列。
示例:
student类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace SelectMany操作符 8 { 9 ///10 /// 学生类11 /// 12 public class Student13 {14 //姓名15 public string Name { get; set; }16 //成绩17 public int Score { get; set; }18 //构造函数19 public Student(string name, int score)20 {21 this.Name = name;22 this.Score = score;23 }24 }25 }
teacher类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace SelectMany操作符 8 { 9 ///10 /// Teacher类11 /// 12 public class Teacher13 {14 //姓名15 public string Name { get; set; }16 //学生集合17 public ListStudents { get; set; }18 19 public Teacher(string name, List students)20 {21 this.Name = name;22 this.Students = students;23 }24 }25 }
Program类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace SelectMany操作符 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 //使用集合初始化器初始化Teacher集合14 Listteachers = new List { 15 new Teacher("徐老师",16 new List (){17 new Student("宋江",80),18 new Student("卢俊义",95),19 new Student("朱武",45)20 }21 ),22 new Teacher("姜老师",23 new List (){24 new Student("林冲",90),25 new Student("花荣",85),26 new Student("柴进",58)27 }28 ),29 new Teacher("樊老师",30 new List (){31 new Student("关胜",100),32 new Student("阮小七",70),33 new Student("时迁",30)34 }35 )36 };37 38 //问题:查询Score小于60的学生39 //方法1:循环遍历、会有性能的损失40 foreach (Teacher t in teachers)41 {42 foreach (Student s in t.Students)43 {44 if (s.Score < 60)45 {46 Console.WriteLine("姓名:" + s.Name + ",成绩:"+s.Score);47 }48 }49 }50 51 //查询表达式52 //方法2:使用SelectMany 延迟加载:在不需要数据的时候,就不执行调用数据,能减轻程序和数据库的交互,可以提供程序的性能,执行循环的时候才去访问数据库取数据 53 //直接返回学生的数据54 var query = from t in teachers55 from s in t.Students56 where s.Score < 6057 select s;58 foreach (var item in query)59 {60 Console.WriteLine("姓名:" + item.Name + ",成绩:"+item.Score);61 }62 //只返回老师的数据63 var query1 = from t in teachers64 from s in t.Students65 where s.Score < 6066 select new { 67 t,68 teacherName=t.Name,69 student=t.Students.Where(p=>p.Score<60).ToList()70 };71 foreach (var item in query1)72 {73 Console.WriteLine("老师姓名:" + item.teacherName + ",学生姓名:" +item.student.FirstOrDefault().Name+ ",成绩:" + item.student.FirstOrDefault().Score);74 }75 // 使用匿名类 返回老师和学生的数据76 var query2 = from t in teachers77 from s in t.Students78 where s.Score < 6079 select new { teacherName=t.Name, studentName=s.Name,studentScore=s.Score }; 80 foreach (var item in query2)81 {82 Console.WriteLine("老师姓名:" + item.teacherName + ",学生姓名:" + item.studentName + ",成绩:" + item.studentScore);83 }84 85 //使用查询方法86 var query3 = teachers.SelectMany(p => p.Students.Where(t=>t.Score<60).ToList());87 foreach (var item in query3)88 {89 Console.WriteLine("姓名:" + item.Name + ",成绩:" + item.Score);90 }91 Console.ReadKey();92 93 }94 }95 }