SelectMany 是 LINQ 中用于展平集合的强大操作符。让我们详细了解它的使用1. 基本用法12345678// 基础示例var lists newListListint {newListint { 1, 2, 3 },newListint { 4, 5, 6 }};var flattened lists.SelectMany(x x);// 结果: [1, 2, 3, 4, 5, 6]2. 带索引的 SelectMany12var result lists.SelectMany((list, index) list.Select(item $列表{index}: {item}));3. 实际应用场景一对多关系展平1234567891011121314151617publicclassStudent{publicstringName {get;set; }publicListCourse Courses {get;set; }}// 获取所有学生的所有课程var allCourses students.SelectMany(s s.Courses);// 带学生信息的课程列表var studentCourses students.SelectMany(student student.Courses,(student, course) new{StudentName student.Name,CourseName course.Name});字符串处理123string[] words {Hello,World};var letters words.SelectMany(word word.ToLower());// 结果: [h,e,l,l,o,w,o,r,l,d]4. 查询语法1234567// 方法语法var result students.SelectMany(s s.Courses);// 等价的查询语法var result from studentinstudentsfrom courseinstudent.Coursesselect course;5. 高级用法条件过滤1234567var result students.SelectMany(student student.Courses.Where(c c.Credits 3),(student, course) new{Student student.Name,Course course.Name,Credits course.Credits});多层展平1234var departments newListDepartment();var result departments.SelectMany(d d.Teams).SelectMany(t t.Employees);注意事项性能考虑- SelectMany 会创建新的集合- 大数据量时注意内存使用- 考虑使用延迟执行空值处理123// 处理可能为null的集合var result students.SelectMany(s s.Courses ?? Enumerable.EmptyCourse());常见错误- 忘记处理空集合- 嵌套 SelectMany 过深- 返回类型不匹配SelectMany 在处理嵌套集合、一对多关系时非常有用掌握它可以大大简化复杂数据处理的代码
C# LINQ SelectMany方法详解
SelectMany 是 LINQ 中用于展平集合的强大操作符。让我们详细了解它的使用1. 基本用法12345678// 基础示例var lists newListListint {newListint { 1, 2, 3 },newListint { 4, 5, 6 }};var flattened lists.SelectMany(x x);// 结果: [1, 2, 3, 4, 5, 6]2. 带索引的 SelectMany12var result lists.SelectMany((list, index) list.Select(item $列表{index}: {item}));3. 实际应用场景一对多关系展平1234567891011121314151617publicclassStudent{publicstringName {get;set; }publicListCourse Courses {get;set; }}// 获取所有学生的所有课程var allCourses students.SelectMany(s s.Courses);// 带学生信息的课程列表var studentCourses students.SelectMany(student student.Courses,(student, course) new{StudentName student.Name,CourseName course.Name});字符串处理123string[] words {Hello,World};var letters words.SelectMany(word word.ToLower());// 结果: [h,e,l,l,o,w,o,r,l,d]4. 查询语法1234567// 方法语法var result students.SelectMany(s s.Courses);// 等价的查询语法var result from studentinstudentsfrom courseinstudent.Coursesselect course;5. 高级用法条件过滤1234567var result students.SelectMany(student student.Courses.Where(c c.Credits 3),(student, course) new{Student student.Name,Course course.Name,Credits course.Credits});多层展平1234var departments newListDepartment();var result departments.SelectMany(d d.Teams).SelectMany(t t.Employees);注意事项性能考虑- SelectMany 会创建新的集合- 大数据量时注意内存使用- 考虑使用延迟执行空值处理123// 处理可能为null的集合var result students.SelectMany(s s.Courses ?? Enumerable.EmptyCourse());常见错误- 忘记处理空集合- 嵌套 SelectMany 过深- 返回类型不匹配SelectMany 在处理嵌套集合、一对多关系时非常有用掌握它可以大大简化复杂数据处理的代码