Voir l’exemple de code ci-dessous. J’ai besoin que la ArrayList
soit une liste générique.
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;
Essayez ce qui suit
var list = arrayList.Cast().ToList();
Cela ne fonctionnera que si vous utilisez le compilateur C # 3.5, car il tire parti de certaines méthodes d’extension définies dans le framework 3.5.
Ceci est inefficace (il fait un tableau intermédiaire inutilement) mais est concis et fonctionnera sur .NET 2.0:
List newList = new List (arrayList.ToArray(typeof(int)));
Que diriez-vous d’utiliser une méthode d’extension?
De 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; } }
Dans .Net standard 2, utiliser Cast
est préférable:
ArrayList al = new ArrayList(); al.AddRange(new[]{"Micheal", "Jack", "Sarah"}); List list = al.Cast ().ToList();
Cast
etToList
sont des méthodes d’extension dans la classeSystem.Linq.Enumerable
.