在 .Net 2.0 中从 ArrayList 转换为 List 的最佳方法是什么
我有一个 BookingData
类型的 ArrayList
到 List
?
我正在使用 .net 2.0,所以我不能使用 arrayList.Cast
谢谢。
I have a ArrayList
of type BookingData
to List<BookingData>
?
I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList()
, and I dont want to make here foreach loop , do you have better ideas ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须使用
foreach
:You have to use
foreach
:ToList() 方法只不过是用于创建列表表示形式的合成糖,但在内部它也使用循环来生成列表项。
因此使用 foreach 迭代器块更加干净和简单。
ToList() method is nothing but the Synthetic sugar for creating a List representation but internally it is also using loop to generate the list item.
so it is much cleaner and simpler to use a foreach iterator block.
使用此方法:
然后您可以:
Use this method:
Then you can:
让我们保持简单:
Let's keep it simple:
请注意,某些必须枚举数组列表才能构造
List
;这只是你是否自己做或将其留给其他(框架/实用程序)方法的问题。如果这是一次性的,那么您希望避免的解决方案(使用“就地”
foreach
循环进行转换)是一个完全合理的选择。如果您发现自己经常这样做,您可以将其提取到通用实用程序方法中,如 cdhowie 的答案所示。如果您的限制只是必须定位 .NET 2.0(但可以使用 C# 3),请考虑LINQBridge,它是 .NET 2.0 的 LINQ to Objects 的重新实现。这将让您无需更改即可使用您提供的
Cast
示例。它也适用于 C# 2,但您不会获得扩展方法语法、更好的类型推断等的好处。如果您不关心性能,也不想惹上麻烦编写实用方法时,您可以使用内置的
ArrayList.ToArray
方法通过创建一个与List
配合良好的中间数组来提供帮助(这并不比foreach):最后,我建议,如果可能的话,完全放弃使用过时的非泛型集合类。
Do note that something is going to have to enumerate the array-list to construct the
List<T>
; its only a matter of whether you do it yourself or leave it to some other (framework / utility) method.If this is a one-off, the solution that you wish to avoid (using an "in-place"
foreach
loop to do the conversion) is a perfectly reasonable option. If you find yourself doing this quite often, you could extract that out into a generic utility method, as in cdhowie's answer.If your restriction is only that you must target .NET 2.0 (but can use C# 3), consider LINQBridge, which is a reimplementation of LINQ to Objects for .NET 2.0. This will let you use the
Cast
sample you've provided without change. It will work on C# 2 too, but you won't get the benefits of the extension-method syntax, better type-inference etc.If you don't care about performance, nor do you want to go to the trouble of writing a utility method, you could use the in-built
ArrayList.ToArray
method to help out, by creating an intermediary array that plays well withList<T>
(this isn't all that shorter than a foreach):Finally, I would suggest, if possible to abandon using the obsolete non-generic collection-classes altogether.