如何在不使用foreach的情况下将ArrayList转换为强类型通用列表?

请参阅下面的代码示例。 我需要ArrayList作为通用List。 我不想使用foreach

 ArrayList arrayList = GetArrayListOfInts(); List intList = new List(); //Can this foreach be condensed into one line? foreach (int number in arrayList) { intList.Add(number); } return intList; 

请尝试以下方法

 var list = arrayList.Cast().ToList(); 

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

这是低效的(它不必要地创建一个中间数组)但是简洁并且可以在.NET 2.0上运行:

 List newList = new List(arrayList.ToArray(typeof(int))); 

使用扩展方法怎么样?

来自http://www.dotnetperls.com/convert-arraylist-list :

 using System; using System.Collections; using System.Collections.Generic; static class Extensions { ///  /// Convert ArrayList to List. ///  public static List ToList(this ArrayList arrayList) { List list = new List(arrayList.Count); foreach (T instance in arrayList) { list.Add(instance); } return list; } } 

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

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

CastToListSystem.Linq.Enumerable类中的扩展方法。