C# LINQ SelectMany方法詳解
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);
// 結(jié)果: [1, 2, 3, 4, 5, 6]2. 帶索引的 SelectMany
var result = lists.SelectMany((list, index) =>
list.Select(item => $"列表{index}: {item}"));3. 實際應用場景
一對多關(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)系時非常有用,掌握它可以大大簡化復雜數(shù)據(jù)處理的代碼
到此這篇關(guān)于C# LINQ SelectMany方法詳解的文章就介紹到這了,更多相關(guān)C# LINQ SelectMany內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法
這篇文章主要介紹了C#實現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法,比較實用的功能,需要的朋友可以參考下2014-07-07
C# 7.0之ref locals and returns(局部變量和引用返回)
這篇文章主要介紹了C# 7.0之ref locals and returns,即局部變量和引用返回,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
C#提取文件時間戳實現(xiàn)實現(xiàn)與性能優(yōu)化
這篇文章主要為大家詳細介紹了如何高效地從CAN ASC文件中提取時間戳數(shù)據(jù),并分享一個高性能的C#實現(xiàn)方案,有需要的小伙伴可以跟隨小編一起學習一下2025-06-06
在C#中調(diào)用Python腳本實現(xiàn)跨語言功能集成
隨著現(xiàn)代應用程序的復雜性和多樣性不斷增加,跨語言集成已成為一種常見的開發(fā)實踐,C# 和 Python 是兩種廣泛使用的編程語言,本文將詳細介紹如何在 C# 中調(diào)用 Python 腳本,并通過傳遞參數(shù)實現(xiàn)功能的跨語言集成,需要的朋友可以參考下2026-03-03

