LINQ SelectMany的应用场景

 

示例 1:多层集合展平

假设你有一个列表,每个元素都是一个字符串数组,你想将所有的字符串展平成一个单一的字符串列表。

 

 

示例 2:嵌套循环

假设你有一个用户列表,每个用户有一个订单列表,你想获取所有用户的订单列表。

 

示例 3:多对多关系

假设你有一个学生列表,每个学生选修了多门课程,你想获取所有学生选修的所有课程。

复制代码
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // 学生类
        class Student
        {
            public string Name { get; set; }
            public List<string> Courses { get; set; }
        }

        // 学生列表
        List<Student> students = new List<Student>
        {
            new Student { Name = "Alice", Courses = new List<string> { "Math", "Physics" } },
            new Student { Name = "Bob", Courses = new List<string> { "Chemistry", "Biology" } },
            new Student { Name = "Charlie", Courses = new List<string> { "History", "Geography" } }
        };

        // 使用 SelectMany 获取所有学生选修的所有课程
        List<string> allCourses = students.SelectMany(student => student.Courses).ToList();

        // 输出所有课程
        foreach (string course in allCourses)
        {
            Console.WriteLine(course);
        }
    }
}
复制代码

 

posted @   katesharing  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示