将 IEnumerable转换为 IEnumerable的最佳方式 到 T[]
从通用 IEnumerable
实现转换为 T 数组的最佳方法是什么? 我当前的解决方案如下所示:
IEnumerable<string> foo = getFoo();
string[] bar = new List<string>(foo).ToArray();
通过 List
进行传输似乎是不必要的,但我还没有找到更好的方法来做到这一点。
注意:我在这里使用 C# 2.0。
What is the best way to convert from a generic IEnumerable<T>
implementation to an array of T? The current solution I have looks like the following:
IEnumerable<string> foo = getFoo();
string[] bar = new List<string>(foo).ToArray();
The transfer through a List<T>
seems unneccesary, but I haven't been able to find a better way to do it.
Note: I'm working in C# 2.0 here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
.NET 3.0 及更高版本:
调用
扩展方法,它的作用与下面几乎相同,执行类型嗅探和一些其他优化。IEnumerable
上的 ToArray.NET 2.0 及之前版本:
一般来说,使用
List
将使用IEnumerable< 进行初始化;T>
,然后调用ToArray
可能是最简单的方法。List
的构造函数将检查IEnumerable
以查看它是否实现ICollection
获取项目数以正确初始化列表的容量。 如果没有,它将正常扩展。当然,您最终可能会创建许多
List
实例,只是为了将IEnumerable
转换为T[]
。 为此,您可以编写自己的方法,但实际上只是复制List
中已经存在的代码。.NET 3.0 and after:
Call the
ToArray
extension method onIEnumerable<T>
, it does nearly the same as below, performing type sniffing and some other optimizations..NET 2.0 and before:
Generally speaking, using a
List<T>
which will be initialized with theIEnumerable<T>
and then callingToArray
is probably the easiest way to do this.The constructor for
List<T>
will check theIEnumerable<T>
to see if it implementsICollection<T>
to get the count of items to properly initialize the capacity of the list. If not, it will expand as normal.Of course, you might end up creating a number of
List<T>
instances just for the purpose of transformingIEnumerable<T>
toT[]
. To that end, you can write your own method, but you would really just be duplicating the code that exists inList<T>
already.做一点 .NET Reflector 看起来 Linq ToArray 扩展方法基本上与通过 List<> 传递 IEnumerable 执行相同的操作。 Buffer 类是一个内部类,但其行为似乎与 List<> 非常相似。
Doing a little .NET Reflector it looks like the Linq ToArray extension method basically does the same thing as passing the IEnumerable through a List<>. The Buffer class is an internal, but the behavior seems very similar to List<>.
如果无法确定数组的长度,那么这是最好的方法。
IEnumerable 中没有任何内容可以让您确定长度,但也许您的代码有办法找到另一种方法。 如果是这样,请使用它来构造一个数组。
If there's no way to determine the length of the array, then that's the best way.
There's nothing in IEnumerable that will let you determine the length, but perhaps your code has a way of finding out another way. If so, use that to construct an array.