首页 / 教程列表 / LINQ教程 / LINQ操作符之SelectMany

LINQ操作符之SelectMany

968 更新于: 2022-03-23 读完约需 8 分钟

定义

LINQ的SelectMany操作符是将序列的每个元素投影到IEnumerable<T>并将结果序列合并为一个序列。这意味着SelectMany操作符组合来自一系列结果的记录,然后将其转换为一个结果。

SelectMany示例一

在看完SelectMany操作符的定义后,可能你脑子里还是一片空白。不用着急,下面我们以简单的示例来进一步学习SelectMany投影操作符。

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTutorial
{
    public class MyProgram
    {
        static void Main(string[] args)
        {
            var list = new List<string> { "Csharp", "JavaScript", "Golang" };
            var result = list.SelectMany(x => x);
            Console.WriteLine(string.Join(",", result));
            Console.ReadKey();
        }
    }
}

以上代码片段中,使用SelectMany将字符串集合中的每个字符串都分解成字符,然后再将其合并成一个字符集合,得到的最终result类型为IEnumerable<char>,如下图:

输出结果为:

SelectMany示例二

以下是一个使用SelectMany投影操作符操作嵌套集合的示例。示例中,有一个宠物主人的集合petOwners,每个宠物主人又拥有一个或者多个宠物。现要求从这些集合中找出以字母S开头的宠物名称及其主人的名字,使用SelectMany实现代码如下:

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTutorial
{
    public class MyProgram
    {
        static void Main(string[] args)
        {
            PetOwner[] petOwners =
            {
                new PetOwner { Name="Higa",
                    Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",
                    Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",
                    Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",
                    Pets = new List<string>{ "Dusty" } }
            };

            var query =
                petOwners
                    .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
                    .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
                    .Select(ownerAndPet =>
                        new
                        {
                            Owner = ownerAndPet.petOwner.Name,
                            Pet = ownerAndPet.petName
                        }
                    );

            foreach (var obj in query)
            {
                Console.WriteLine(obj);
            }

            Console.ReadKey();
        }
    }

    class PetOwner
    {
        public string Name { get; set; }
        public List<string> Pets { get; set; }
    }
}

运行结果:

{ Owner = Higa, Pet = Scruffy }
{ Owner = Higa, Pet = Sam }
{ Owner = Ashkenazi, Pet = Sugar }
{ Owner = Price, Pet = Scratches }

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

本文永久链接码友网 » LINQ教程 » LINQ操作符之SelectMany 分享:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册