关于C#中的Select与SelectMany方法

2024-01-19 21:44

本文主要是介绍关于C#中的Select与SelectMany方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Select

将序列中的每个元素投影到新表单。

实例1

IEnumerable<int> squares =Enumerable.Range(1, 10).Select(x => x * x);foreach (int num in squares)
{Console.WriteLine(num);
}
/*This code produces the following output:149162536496481100
*/

实例2 

string[] fruits = { "apple", "banana", "mango", "orange","passionfruit", "grape" };var query =fruits.Select((fruit, index) =>new { index, str = fruit.Substring(0, index) });foreach (var obj in query)
{Console.WriteLine("{0}", obj);
}/*This code produces the following output:{index=0, str=}{index=1, str=b}{index=2, str=ma}{index=3, str=ora}{index=4, str=pass}{index=5, str=grape}
*/

SelectMany

将序列的每个元素投影到 IEnumerable<T> 并将结果序列合并为一个序列。

实例1:

class PetOwner
{public string Name { get; set; }public List<String> Pets { get; set; }
}public static void SelectManyEx1()
{PetOwner[] petOwners ={ new PetOwner { Name="Higa, Sidney",Pets = new List<string>{ "Scruffy", "Sam" } },new PetOwner { Name="Ashkenazi, Ronen",Pets = new List<string>{ "Walker", "Sugar" } },new PetOwner { Name="Price, Vernette",Pets = new List<string>{ "Scratches", "Diesel" } } };// Query using SelectMany().IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);Console.WriteLine("Using SelectMany():");// Only one foreach loop is required to iterate// through the results since it is a// one-dimensional collection.foreach (string pet in query1){Console.WriteLine(pet);}// This code shows how to use Select()// instead of SelectMany().IEnumerable<List<String>> query2 =petOwners.Select(petOwner => petOwner.Pets);Console.WriteLine("\nUsing Select():");// Notice that two foreach loops are required to// iterate through the results// because the query returns a collection of arrays.foreach (List<String> petList in query2){foreach (string pet in petList){Console.WriteLine(pet);}Console.WriteLine();}
}/*This code produces the following output:Using SelectMany():ScruffySamWalkerSugarScratchesDieselUsing Select():ScruffySamWalkerSugarScratchesDiesel
*/

可以理解为,selectmany将二维平展为一维,构建了一个新的集合

实例2

class PetOwner
{public string Name { get; set; }public List<string> Pets { get; set; }
}public static void SelectManyEx3()
{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" } } };// Project the pet owner's name and the pet's name.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});// Print the results.foreach (var obj in query){Console.WriteLine(obj);}
}// This code produces the following output:
//
// {Owner=Higa, Pet=Scruffy}
// {Owner=Higa, Pet=Sam}
// {Owner=Ashkenazi, Pet=Sugar}
// {Owner=Price, Pet=Scratches}

函数原型

public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,System.Collections.Generic.IEnumerable<TCollection>> collectionSelector, Func<TSource,TCollection,TResult> resultSelector);

这里需要说明: 第一个委托执行的结果集会作为第二个委托的第二个参数传递

将上述代码简化如下:

 var query = petOwner.SelectMany(a => a.Pets, (a, b) => new { a, b});

这里的a就是petOwner集合本身,b就是a.Pets生成的新的集合。

所有上面的例子我们可以修改的更简单点,可以得到同样的结果

 var query =petOwners.SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner.Name, petName }).Where(ownerAndPet => ownerAndPet.petName.StartsWith("S")).Select(ownerAndPet => ownerAndPet); //这里的select也可以去掉

这篇关于关于C#中的Select与SelectMany方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/623787

相关文章

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

C#读写文本文件的多种方式详解

《C#读写文本文件的多种方式详解》这篇文章主要为大家详细介绍了C#中各种常用的文件读写方式,包括文本文件,二进制文件、CSV文件、JSON文件等,有需要的小伙伴可以参考一下... 目录一、文本文件读写1. 使用 File 类的静态方法2. 使用 StreamReader 和 StreamWriter二、二进

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()