Search code examples
c#.net-2.0

What is the best way to cast from ArrayList to List in .Net 2.0


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.


Solution

  • 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.

    1. 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.

    2. 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.

    3. 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.