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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论