1. 程式人生 > >LINQ操作符二:SelectMany

LINQ操作符二:SelectMany

ram logs man from item 問題: 不執行 rst 初始化

SelectMany操作符提供了將多個from子句組合起來的功能,相當於數據庫中的多表連接查詢,它將每個對象的結果合並成單個序列。

示例:

 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 Program
10     {
11         static void Main(string
[] args) 12 { 13 //使用集合初始化器初始化Teacher集合 14 List<Teacher> teachers = new List<Teacher> { 15 new Teacher("徐老師", 16 new List<Student>(){ 17 new Student("宋江",80), 18 new Student("盧俊義",95), 19 new
Student("朱武",45) 20 } 21 ), 22 new Teacher("姜老師", 23 new List<Student>(){ 24 new Student("林沖",90), 25 new Student("花榮",85), 26 new Student("柴進",58) 27 } 28 ),
29 new Teacher("樊老師", 30 new List<Student>(){ 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 teachers 55 from s in t.Students 56 where s.Score < 60 57 select s; 58 foreach (var item in query) 59 { 60 Console.WriteLine("姓名:" + item.Name + ",成績:"+item.Score); 61 } 62 //只返回老師的數據 63 var query1 = from t in teachers 64 from s in t.Students 65 where s.Score < 60 66 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 teachers 77 from s in t.Students 78 where s.Score < 60 79 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 }

LINQ操作符二:SelectMany