gpt4 book ai didi

c# - 如何将 IEnumerables 的 IEnumerable 中的所有元素连接在一起?

转载 作者:太空狗 更新时间:2023-10-29 20:51:43 24 4
gpt4 key购买 nike

以防万一你想知道这是怎么发生的,我正在处理来自 Entity Framework 的一些结果集。

我有一个对象是 IEnumerable<IEnumerable<string>> ;基本上,字符串列表的列表。

我想将所有的字符串列表合并成一个大的字符串列表。

在 C#.net 中执行此操作的最佳方法是什么?

最佳答案

使用 LINQ SelectMany 方法:

IEnumerable<IEnumerable<string>> myOuterList = // some IEnumerable<IEnumerable<string>>...
IEnumerable<String> allMyStrings = myOuterList.SelectMany(sl => sl);

要非常清楚这里发生了什么(因为我讨厌人们认为这是某种巫术的想法,而且我对其他一些人删除了相同的答案感到难过):

SelectMany是一个 extension method (通过语法糖看起来像特定类型的实例方法的静态方法)IEnumerable<T> .它采用您的原始枚举枚举和一个将每个项目转换为枚举的函数。

因为项目已经枚举,转换函数很简单 - 只需返回输入(sl => sl 意思是“获取名为 sl 的参数并返回它”)。 SelectMany 然后依次提供对每个这些的枚举,从而产生您的“扁平化”列表..

关于c# - 如何将 IEnumerables 的 IEnumerable 中的所有元素连接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11958116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com