C# LINQ SelectMany方法詳解
SelectMany 是 LINQ 中用于展平集合的強大操作符。讓我們詳細了解它的使用
1. 基本用法
// 基礎(chǔ)示例
var lists = new List<List<int>> {
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 }
};
var flattened = lists.SelectMany(x => x);
// 結(jié)果: [1, 2, 3, 4, 5, 6]2. 帶索引的 SelectMany
var result = lists.SelectMany((list, index) =>
list.Select(item => $"列表{index}: {item}"));3. 實際應(yīng)用場景
一對多關(guān)系展平
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());
// 結(jié)果: ['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 會創(chuàng)建新的集合
- 大數(shù)據(jù)量時注意內(nèi)存使用
- 考慮使用延遲執(zhí)行
空值處理
// 處理可能為null的集合
var result = students.SelectMany(s =>
s.Courses ?? Enumerable.Empty<Course>());常見錯誤
- 忘記處理空集合
- 嵌套 SelectMany 過深
- 返回類型不匹配
SelectMany 在處理嵌套集合、一對多關(guān)系時非常有用,掌握它可以大大簡化復(fù)雜數(shù)據(jù)處理的代碼
到此這篇關(guān)于C# LINQ SelectMany方法詳解的文章就介紹到這了,更多相關(guān)C# LINQ SelectMany內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#保存listbox中數(shù)據(jù)到文本文件的方法
這篇文章主要介紹了C#保存listbox中數(shù)據(jù)到文本文件的方法,涉及C#操作listbox數(shù)據(jù)的相關(guān)技巧,需要的朋友可以參考下2015-04-04

