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

相关文章

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

浅谈主机加固,六种有效的主机加固方法

在数字化时代,数据的价值不言而喻,但随之而来的安全威胁也日益严峻。从勒索病毒到内部泄露,企业的数据安全面临着前所未有的挑战。为了应对这些挑战,一种全新的主机加固解决方案应运而生。 MCK主机加固解决方案,采用先进的安全容器中间件技术,构建起一套内核级的纵深立体防护体系。这一体系突破了传统安全防护的局限,即使在管理员权限被恶意利用的情况下,也能确保服务器的安全稳定运行。 普适主机加固措施:

webm怎么转换成mp4?这几种方法超多人在用!

webm怎么转换成mp4?WebM作为一种新兴的视频编码格式,近年来逐渐进入大众视野,其背后承载着诸多优势,但同时也伴随着不容忽视的局限性,首要挑战在于其兼容性边界,尽管WebM已广泛适应于众多网站与软件平台,但在特定应用环境或老旧设备上,其兼容难题依旧凸显,为用户体验带来不便,再者,WebM格式的非普适性也体现在编辑流程上,由于它并非行业内的通用标准,编辑过程中可能会遭遇格式不兼容的障碍,导致操

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

【VUE】跨域问题的概念,以及解决方法。

目录 1.跨域概念 2.解决方法 2.1 配置网络请求代理 2.2 使用@CrossOrigin 注解 2.3 通过配置文件实现跨域 2.4 添加 CorsWebFilter 来解决跨域问题 1.跨域概念 跨域问题是由于浏览器实施了同源策略,该策略要求请求的域名、协议和端口必须与提供资源的服务相同。如果不相同,则需要服务器显式地允许这种跨域请求。一般在springbo

AI(文生语音)-TTS 技术线路探索学习:从拼接式参数化方法到Tacotron端到端输出

AI(文生语音)-TTS 技术线路探索学习:从拼接式参数化方法到Tacotron端到端输出 在数字化时代,文本到语音(Text-to-Speech, TTS)技术已成为人机交互的关键桥梁,无论是为视障人士提供辅助阅读,还是为智能助手注入声音的灵魂,TTS 技术都扮演着至关重要的角色。从最初的拼接式方法到参数化技术,再到现今的深度学习解决方案,TTS 技术经历了一段长足的进步。这篇文章将带您穿越时