代码之家  ›  专栏  ›  技术社区  ›  Curtis White

要使用.Net列出的数组列表?

  •  12
  • Curtis White  · 技术社区  · 14 年前

    如何将arraylist转换/转储为列表?我之所以使用arraylist是因为我使用的是ASP.NET配置文件功能,而且在配置文件中存储列表看起来很痛苦。

    注: 另一种选择是将列表包装到自己的类中,并去掉ArrayList。

    http://www.ipreferjim.com/site/2009/04/storing-generics-in-asp-net-profile-object/

    4 回复  |  直到 6 年前
        1
  •  26
  •   Adam Robinson    14 年前

    最简单的转换方法 ArrayList T 可能是这样(假设您使用的是.NET 3.5或更高版本):

    List<T> list = arrayList.Cast<T>().ToList();
    

    如果您使用的是3.0或更早版本,则必须自己循环:

    List<T> list = new List<T>(arrayList.Count);
    
    foreach(T item in arrayList) list.Add(item);
    
        2
  •  4
  •   Jerod Houghtelling    14 年前

    using System.Linq;

    ArrayList arrayList = new ArrayList();
    arrayList.Add( 1 );
    arrayList.Add( "two" );
    arrayList.Add( 3 );
    
    List<int> integers = arrayList.OfType<int>().ToList();
    

        3
  •  2
  •   Ryan Bennett    14 年前
    ArrayList a = new ArrayList();
    
    object[] array = new object[a.Count];
    
    a.CopyTo(array);
    
    List<object> list = new List<object>(array);
    

        4
  •  0
  •   Tim Schmelter    14 年前

    这在框架中起作用<3.5也是:

    Dim al As New ArrayList()
    al.Add(1)
    al.Add(2)
    al.Add(3)
    Dim newList As New List(Of Int32)(al.ToArray(GetType(Int32)))
    

    List<int> newList = new List<int>(al.ToArray(typeof(int)));