65

以下のコードサンプルを参照してください。ArrayListを一般的なリストにする必要があります。使いたくないforeach

ArrayList arrayList = GetArrayListOfInts();  
List<int> intList = new List<int>();  

//Can this foreach be condensed into one line?  
foreach (int number in arrayList)  
{  
    intList.Add(number);  
}  
return intList;    
4

4 に答える 4

124

以下を試してください

var list = arrayList.Cast<int>().ToList();

これは、3.5 フレームワークで定義された特定の拡張メソッドを利用するため、C# 3.5 コンパイラを使用している場合にのみ機能します。

于 2009-04-24T15:11:27.983 に答える
10

これは非効率的です (不必要に中間配列を作成します) が、簡潔であり、.NET 2.0 で動作します。

List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));
于 2009-04-24T15:16:18.753 に答える
4

拡張メソッドを使用するのはどうですか?

http://www.dotnetperls.com/convert-arraylist-listから:

using System;
using System.Collections;
using System.Collections.Generic;

static class Extensions
{
    /// <summary>
    /// Convert ArrayList to List.
    /// </summary>
    public static List<T> ToList<T>(this ArrayList arrayList)
    {
        List<T> list = new List<T>(arrayList.Count);
        foreach (T instance in arrayList)
        {
            list.Add(instance);
        }
        return list;
    }
}
于 2011-02-22T17:30:13.407 に答える