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.
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 with List<T>
(this isn't all that shorter than a foreach):
ArrayList arrayList = ...
// Create intermediary array
BookingData[] array = (BookingData[]) arrayList.ToArray(typeof(BookingData));
// Create the List<T> using the constructor that takes an IEnumerable<T>
List<BookingData> list = new List<BookingData>(array);
Finally, I would suggest, if possible to abandon using the obsolete non-generic collection-classes altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With