开发者

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 can开发者_Go百科not 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.

  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.


Let's keep it simple:

// 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);


Use this method:

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;
}

Then you can:

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


You have to use foreach:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜