目录- 1. 基本用法
- 2. 带索引的 SelectMany
- 3. 实际应用场景
- 4. 查询语法
- 5. 高级用法
- 注意事项
SelectMany 是 LINQ 中用于展平集合的强大操作符。让我们详细了解它的使用
1. 基本用法
// 基础示例
var lists = new List<List<int>> {
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 }
};
var flattened = lists.SelectMany(x => x);
// 结果: [1, 2, 3, 4, 5, 6]
2. 带索引的 SelectMany
var result = lists.SelectMany((list, index) =>
list.Select(item => $"列表{index}: {item}"));
3. 实际应用场景
一对多关系展平
public class Student
{
public string Name { get; set; }
public List<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
}
);
字符串处理
string[] words = { "Hello", "World" };
var letters = words.SelectMany(word => word.ToLower());
// 结果: ['h','e','l','l','o','w','o','r','l','d']
4. 查询语法
// 方法语法
var result = students.SelectMany(s => s.Courses);
// 等价的查询语法
var result = from student in students
from course in student.Courses
select course;
5. 高级用法
条件过滤
var result = students.SelectMany(
student => student.Courses.Where(c => c.Credits > 3),
(student, course) => new {
Student = student.Name,
Course = course.Name,
Credits = course.Credits
});
多层展平
var departments = new List<Department>();
var result = departments
.SelectMany(d => d.Teams)
.SelectMany(t => t.Employees);
注意事项
性能考虑
- SelectMany 会创建新的集合 - 大数据量时注意内存使用 - 考虑使用延迟执行
空值处理
// 处理可能为null的集合
var result = students.SelectMany(s =>
s.Courses ?? Enumerable.Empty<Course>());
常见错误 - 忘记处理空集合 - 嵌套 SelectMany 过深 - 返回类型不匹配
SelectMany 在处理嵌套集合、一对多关系时非常有用,掌握它可以大大简化复杂数据处理的代码
到此这篇关于C# LINQ SelectMany方法详解的文章就介绍到这了,更多相关C# LINQ SelectMany内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!
您可能感兴趣的文章:- C#中LINQ的Select与SelectMany函数使用
|