关于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

相关文章

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

自定义注解SpringBoot防重复提交AOP方法详解

《自定义注解SpringBoot防重复提交AOP方法详解》该文章描述了一个防止重复提交的流程,通过HttpServletRequest对象获取请求信息,生成唯一标识,使用Redis分布式锁判断请求是否... 目录防重复提交流程引入依赖properties配置自定义注解切面Redis工具类controller

C#如何在Excel文档中获取分页信息

《C#如何在Excel文档中获取分页信息》在日常工作中,我们经常需要处理大量的Excel数据,本文将深入探讨如何利用Spire.XLSfor.NET,高效准确地获取Excel文档中的分页信息,包括水平... 目录理解Excel中的分页机制借助 Spire.XLS for .NET 获取分页信息为什么选择 S

Java调用DeepSeek API的8个高频坑与解决方法

《Java调用DeepSeekAPI的8个高频坑与解决方法》现在大模型开发特别火,DeepSeek因为中文理解好、反应快、还便宜,不少Java开发者都用它,本文整理了最常踩的8个坑,希望对... 目录引言一、坑 1:Token 过期未处理,鉴权异常引发服务中断问题本质典型错误代码解决方案:实现 Token

Nginx 访问控制的多种方法

《Nginx访问控制的多种方法》本文系统介绍了Nginx实现Web访问控制的多种方法,包括IP黑白名单、路径/方法/参数控制、HTTP基本认证、防盗链机制、客户端证书校验、限速限流、地理位置控制等基... 目录一、IP 白名单与黑名单1. 允许/拒绝指定IP2. 全局黑名单二、基于路径、方法、参数的访问控制

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C