net - c# string foreach
在.Net中,如何在不使用foreach的情況下將ArrayList轉換為強類型通用列表? (3)
使用擴展方法怎麼樣?
來自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;
}
}
請參閱下面的代碼示例。 我需要ArrayList
作為通用List。
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;
在.Net標準2中使用Cast<T>
是更好的方法:
ArrayList al = new ArrayList();
al.AddRange(new[]{"Micheal", "Jack", "Sarah"});
List<int> list = al.Cast<int>().ToList();
Cast
和ToList
是System.Linq.Enumerable
類中的擴展方法。
這是低效的(它不必要地創建一個中間數組)但是簡潔並且可以在.NET 2.0上運行:
List<int> newList = new List<int>(arrayList.ToArray(typeof(int)));