当前位置: 首页 > news >正文

关于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也可以去掉

http://www.lryc.cn/news/284417.html

相关文章:

  • CentOS上安装Mellanox OFED
  • 无/自监督去噪(1)——一个变迁:N2N→N2V→HQ-SSL
  • 【24.1.19】
  • 使用mamba替换conda和anaconda配置环境安装软件
  • 鸿蒙开发系列教程(四)--ArkTS语言:基础知识
  • Pix2Pix理论与实战
  • [GN] 后端接口已经写好 初次布局前端需要的操作(例)
  • AIGC:人工智能驱动的数据分析新时代
  • Windows Qt C++ VTK 借助msys环境搭建
  • 尚硅谷Nginx高级配置笔记
  • 论rtp协议的重要性
  • 【Github搭建网站】零基础零成本搭建个人Web网站~
  • unocss+iconify技术在vue项目中使用20000+的图标
  • python 自动化模块 - pyautogui初探
  • UE5 蓝图编辑美化学习
  • 基于动态顺序表实现通讯录项目
  • python使用jupyter记笔记
  • C#封装服务
  • 手写Vue3源码
  • 如何无需重复输入FTP信息来安装WordPress主题和插件
  • 开发安全之:JSON Injection
  • 各种Linux版本安装Docker
  • git中合并分支时出现了代码冲突怎么办
  • 什么是防火墙?
  • tui.calender日历创建、删除、编辑事件、自定义样式
  • OpenHarmonyOS-gn与Ninja
  • Docker部署Traefik结合内网穿透远程访问Dashboard界面
  • 2024年甘肃省职业院校技能大赛信息安全管理与评估 样题二 理论题
  • 从代码到项目管理:程序员的职业跃迁与PMP认证之路
  • 空间形状对结构加法产物的影响