2026/5/24 8:45:21
网站建设
项目流程
SelectMany 是 LINQ 中用于展平集合的强大操作符。让我们详细了解它的使用
1. 基本用法
1 2 3 4 5 6 7 8 | // 基础示例
var lists =newList<List<int>> {
newList<int> { 1, 2, 3 },
newList<int> { 4, 5, 6 }
};
var flattened = lists.SelectMany(x => x);
// 结果: [1, 2, 3, 4, 5, 6]
|
2. 带索引的 SelectMany
1 2 | var result = lists.SelectMany((list, index) =>
list.Select(item => $"列表{index}: {item}"));
|
3. 实际应用场景
一对多关系展平
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | publicclassStudent
{
publicstringName {get;set; }
publicList<Course> 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
}
);
|
字符串处理
1 2 3 | string[] words = {"Hello","World"};
var letters = words.SelectMany(word => word.ToLower());
// 结果: ['h','e','l','l','o','w','o','r','l','d']
|
4. 查询语法
1 2 3 4 5 6 7 | // 方法语法
var result = students.SelectMany(s => s.Courses);
// 等价的查询语法
var result = from studentinstudents
from courseinstudent.Courses
select course;
|
5. 高级用法
条件过滤
1 2 3 4 5 6 7 | var result = students.SelectMany(
student => student.Courses.Where(c => c.Credits > 3),
(student, course) =>new{
Student = student.Name,
Course = course.Name,
Credits = course.Credits
});
|
多层展平
1 2 3 4 | var departments =newList<Department>();
var result = departments
.SelectMany(d => d.Teams)
.SelectMany(t => t.Employees);
|
注意事项
性能考虑
- SelectMany 会创建新的集合
- 大数据量时注意内存使用
- 考虑使用延迟执行
空值处理
1 2 3 | // 处理可能为null的集合
var result = students.SelectMany(s =>
s.Courses ?? Enumerable.Empty<Course>());
|
常见错误
- 忘记处理空集合
- 嵌套 SelectMany 过深
- 返回类型不匹配
SelectMany 在处理嵌套集合、一对多关系时非常有用,掌握它可以大大简化复杂数据处理的代码