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

这仅在使用 C# 3.5 编译器时才有效,因为它利用了 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 回答
1

在 .Net 标准 2 中使用Cast<T>更好的方法:

ArrayList al = new ArrayList();
al.AddRange(new[]{"Micheal", "Jack", "Sarah"});
List<int> list = al.Cast<int>().ToList();

Cast并且ToListSystem.Linq.Enumerable类中的扩展方法。

于 2018-07-04T11:50:12.947 回答