2009-04-24 98 views
52

请参阅下面的代码示例。我需要ArrayList是一个通用的列表。在.Net中,如何在不使用foreach的情况下将ArrayList转换为强类型的泛型列表?

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;  
+0

如果你是不知道,ArrayList中只包含预期的类型,它们进行过滤arrayList.OfType ().ToList()。看到http://stackoverflow.com/a/7845009/52277 – 2013-05-16 21:39:47

回答

102

请尝试以下

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

这只会但因为它利用了在3.5框架中定义的某些扩展方法使用C#编译器3.5工作。

+0

虽然我已经明确地使用过这个,但我正在考虑装箱/取消装箱。这不会从表现中收回吗?有时我发现漂亮的代码是以牺牲速度和资源为代价的...... – 2009-04-24 15:15:22

+6

这只是将它放在ArrayList中的一个结果。只要将每个成员都转换回int,就可以在性能方面做到最好。 – mquander 2009-04-24 15:17:11

9

这是低效的(它使一个中间阵列不必要地),但是简洁和.NET 2.0将工作:

List<int> newList = new List<int>(arrayList.ToArray(typeof(int))); 
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; 
    } 
} 
相关问题