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

Do I have a ArrayListtype BookingDatabefore List<BookingData>?

I use .net 2.0, so I can’t use arrayList.Cast<int>().ToList(), and I don’t want to do a foreach loop here, do you have any better ideas?

Thank.

+5
source share
5 answers

Note that something will have to list the list of arrays to build List<T>; it is only a question of whether you do it yourself or leave it to some other method (framework / utility).

  • , , ( " " foreach ), . , , , cdhowie.

  • , .NET 2.0 ( # 3), LINQBridge, LINQ .NET 2.0. Cast, . # 2, , - ..

  • , ArrayList.ToArray, , , List<T> ( , , 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);

, , , .

+11

:

// untested
List<T> ConvertArrayList<T>(ArrayList data)
{
    List<T>  result = new List<T> (data.Count);
    foreach (T item in data)
      result.Add(item);
    return result;
}

...

List<BookingData> newList = ConvertArrayList<BookingData>(oldList);
+2

:

public static List<T> ConvertToList<T>(ArrayList list)
{
    if (list == null)
        throw new ArgumentNullException("list");

    List<T> newList = new List<T>(list.Count);

    foreach (object obj in list)
        newList.Add((T)obj);

    // If you really don't want to use foreach:
    // for (int i = 0; i < list.Count; i++)
    //     newList.Add((T)list[i]);

    return newList;
}

:

List<BookingData> someList = ConvertToList<BookingData>(someArrayList);
+1

foreach:

        foreach (Object item in list1)
        {
            list2.Add((BookingData)item);
        }
0

ToList() - , List, .

foreach.

0

All Articles