>使用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中文网其他相关文章!