System.Array到列表的转换

昨晚我梦到以下事情是不可能的。但是在同一个梦中,SO的某人告诉我否则。因此,我想知道是否有可能转换System.Array为List


Array ints = Array.CreateInstance(typeof(int), 5);

ints.SetValue(10, 0);

ints.SetValue(20, 1);

ints.SetValue(10, 2);

ints.SetValue(34, 3);

ints.SetValue(113, 4);


List<int> lst = ints.OfType<int>(); // not working


Smart猫小萌
浏览 420回答 3
3回答

汪汪一只猫

减轻自己的痛苦...using System.Linq;int[] ints = new [] { 10, 20, 10, 34, 113 };List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.也可以...List<int> lst = new List<int> { 10, 20, 10, 34, 113 };要么...List<int> lst = new List<int>();lst.Add(10);lst.Add(20);lst.Add(10);lst.Add(34);lst.Add(113);要么...List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });要么...var lst = new List<int>();lst.AddRange(new int[] { 10, 20, 10, 34, 113 });

手掌心

List的构造函数重载也可以工作...但是我想这将需要一个强类型数组。//public List(IEnumerable<T> collection)var intArray = new[] { 1, 2, 3, 4, 5 };var list = new List<int>(intArray);...用于Array类var intArray = Array.CreateInstance(typeof(int), 5);for (int i = 0; i < 5; i++)&nbsp; &nbsp; intArray.SetValue(i, i);var list = new List<int>((int[])intArray);

MM们

有趣的是,没人回答这个问题,OP不是使用强类型,int[]而是使用Array。您必须将Array转换为实际的int[],然后才能使用ToList:List<int> intList = ((int[])ints).ToList();请注意,Enumerable.ToList调用列表构造函数将首先检查是否可以将参数强制转换为ICollection<T>(数组实现)该参数,然后它将使用更有效的ICollection<T>.CopyTo方法来代替枚举序列。
打开App,查看更多内容
随时随地看视频慕课网APP