LINQ操作符SelectMany的用法

SelectMany操作符提供了将多个from子句组合起来的功能,相当于数据库中的多表连接查询,它将每个对象的结果合并成单个序列。
示例:
student类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelectMany操作符{/// /// 学生类/// public class Student{//姓名public string Name { get; set; }//成绩public int Score { get; set; }//构造函数public Student(string name, int score){this.Name = name; this.Score = score; }}}

teacher类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelectMany操作符{/// /// Teacher类/// public class Teacher{//姓名public string Name { get; set; }//学生集合public List Students { get; set; }public Teacher(string name, List students){this.Name = name; this.Students = students; }}}

Program类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelectMany操作符{class Program{static void Main(string[] args){//使用集合初始化器初始化Teacher集合List teachers = new List {new Teacher("徐老师",new List(){new Student("宋江",80),new Student("卢俊义",95),new Student("朱武",45)}),new Teacher("姜老师",new List(){new Student("林冲",90),new Student("花荣",85),new Student("柴进",58)}),new Teacher("樊老师",new List(){new Student("关胜",100),new Student("阮小七",70),new Student("时迁",30)})}; //问题:查询Score小于60的学生//方法1:循环遍历、会有性能的损失foreach (Teacher t in teachers){foreach (Student s in t.Students){if (s.Score < 60){Console.WriteLine("姓名:" + s.Name + ",成绩:"+s.Score); }}}//查询表达式//方法2:使用SelectMany延迟加载:在不需要数据的时候,就不执行调用数据,能减轻程序和数据库的交互,可以提供程序的性能,执行循环的时候才去访问数据库取数据//直接返回学生的数据var query = from t in teachersfrom s in t.Studentswhere s.Score < 60select s; foreach (var item in query){Console.WriteLine("姓名:" + item.Name + ",成绩:"+item.Score); }//只返回老师的数据var query1 = from t in teachersfrom s in t.Studentswhere s.Score < 60select new {t,teacherName=t.Name,student=t.Students.Where(p=>p.Score<60).ToList()}; foreach (var item in query1){Console.WriteLine("老师姓名:" + item.teacherName + ",学生姓名:" +item.student.FirstOrDefault().Name+ ",成绩:" + item.student.FirstOrDefault().Score); }// 使用匿名类 返回老师和学生的数据var query2 = from t in teachersfrom s in t.Studentswhere s.Score < 60select new { teacherName=t.Name, studentName=s.Name,studentScore=s.Score }; foreach (var item in query2){Console.WriteLine("老师姓名:" + item.teacherName + ",学生姓名:" + item.studentName + ",成绩:" + item.studentScore); }//使用查询方法var query3 = teachers.SelectMany(p => p.Students.Where(t=>t.Score<60).ToList()); foreach (var item in query3){Console.WriteLine("姓名:" + item.Name + ",成绩:" + item.Score); }Console.ReadKey(); }}}

【LINQ操作符SelectMany的用法】到此这篇关于LINQ操作符SelectMany的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读