首页 > 后端开发 > C++ > Linq的SelectMany()方法如何将整数的嵌套列表变平?

Linq的SelectMany()方法如何将整数的嵌套列表变平?

Patricia Arquette
发布: 2025-01-26 15:36:09
原创
401 人浏览过

How Can LINQ's SelectMany() Method Flatten a Nested List of Integers?

>使用Linq的SelectMany()来平坦的嵌套整数列表

>

LINQ查询通常会产生嵌套集合,例如IEnumerable<List<int>>SelectMany()方法有效地将它们弄平到单个列表中。

>

挑战:

假设linq查询返回整数列表(IEnumerable<List<int>>)的列表。任务是将这些内部列表组合成一个单一的一维List<int>

说明性示例:

从以下输入列表开始:

<code>[1, 2, 3, 4] and [5, 6, 7]</code>
登录后复制

所需的输出为:

<code>[1, 2, 3, 4, 5, 6, 7]</code>
登录后复制

>使用SelectMany():

解决方案

linq's SelectMany()简化了此过程。 这是将嵌套列表弄平的方法:

>
<code class="language-csharp">var nestedList = new List<List<int>> { new List<int> { 1, 2, 3, 4 }, new List<int> { 5, 6, 7 } };
var flattenedList = nestedList.SelectMany(innerList => innerList).ToList(); </code>
登录后复制

>说明:

  • nestedList:这代表列表的输入列表。
  • >
  • SelectMany(innerList => innerList):这是解决方案的核心。 SelectMany()innerList中遍历每个nestedList。 lambda表达式innerList => innerList简单地将每个内部列表投射到自身上,有效地解开嵌套。
  • .ToList():这将所得的扁平序列转换为List<int>>。
此简洁的代码有效地扁平了嵌套列表,提供了所需的单维列表。

以上是Linq的SelectMany()方法如何将整数的嵌套列表变平?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板