C#高级语法:Linq中使用SelectMany解决列表子项提取、双重for循环的问题
一、列表子项提取
class Program
{
static void Main()
{
var students = new List<Student>
{
new Student { Name = "Alice", Courses = new List<string> { "Math", "Science" } },
new Student { Name = "Bob", Courses = new List<string> { "English", "History" } },
new Student { Name = "Charlie", Courses = new List<string> { "Art", "Music" } }
};
//注意:x.Courses的类型是List<string>,SelectMany提取后的结果类型不变,一样是List<string>
List<string> course_list = students.SelectMany(x => x.Courses).ToList();//["Math", "Science", "English", "History", "Art", "Music"]
}
}
二、双重for循环
class Program
{
static void Main()
{
var students = new List<string> { "Alice", "Bob", "Charlie" };
var grades = new List<int> { 90, 80, 85 };
//x是students的子项,y是grades的子项,第二入参是x和y,出参可以自定义类型
var result = students.SelectMany(x => grades, (x, y) => new { Name = x, Score = y });// 主列表.SelectMany(x => 次列表, 入参为x和y出参可自定义的委托)
foreach (var item in result)
{
Console.WriteLine($"{item.Name} :{item.Score}");
}
/*
Alice :90
Alice :80
Alice :85
Bob :90
Bob :80
Bob :85
Charlie :90
Charlie :80
Charlie :85
*/
}
}
三、笛卡尔积(扩展)
C#高级:结合Linq的SelectMany方法实现笛卡尔积效果_c# selectmany-CSDN博客