昨晚我梦见以下是不可能的.但是在同一个梦里,来自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);
Run Code Online (Sandbox Code Playgroud)
至
List<int> lst = ints.OfType<int>(); // not working
Run Code Online (Sandbox Code Playgroud)
Dav*_*ave 393
为自己省点痛苦......
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.
Run Code Online (Sandbox Code Playgroud)
也可以......
List<int> lst = new List<int> { 10, 20, 10, 34, 113 };
Run Code Online (Sandbox Code Playgroud)
要么...
List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);
Run Code Online (Sandbox Code Playgroud)
要么...
List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });
Run Code Online (Sandbox Code Playgroud)
要么...
var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
Run Code Online (Sandbox Code Playgroud)
Mat*_*ted 77
List也有一个构造函数重载可以工作......但我想这需要一个强类型数组.
//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);
Run Code Online (Sandbox Code Playgroud)
...对于Array类
var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
Run Code Online (Sandbox Code Playgroud)
Tim*_*ter 56
有趣的是,没有人回答这个问题,OP不是使用强类型int[]而是使用Array.
你必须将其Array转换为实际的内容int[],然后你可以使用ToList:
List<int> intList = ((int[])ints).ToList();
Run Code Online (Sandbox Code Playgroud)
请注意,Enumerable.ToList调用列表构造函数首先检查参数是否可以转换为ICollection<T>(数组实现的),然后它将使用更有效的ICollection<T>.CopyTo方法而不是枚举序列.
小智 27
最简单的方法是:
int[] ints = new [] { 10, 20, 10, 34, 113 };
List<int> lst = ints.ToList();
Run Code Online (Sandbox Code Playgroud)
要么
List<int> lst = new List<int>();
lst.AddRange(ints);
Run Code Online (Sandbox Code Playgroud)
小智 7
如果要将枚举数组作为列表返回,可以执行以下操作.
using System.Linq;
public List<DayOfWeek> DaysOfWeek
{
get
{
return Enum.GetValues(typeof(DayOfWeek))
.OfType<DayOfWeek>()
.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
在vb.net中只需这样做
mylist.addrange(intsArray)
Run Code Online (Sandbox Code Playgroud)
或者
Dim mylist As New List(Of Integer)(intsArray)
Run Code Online (Sandbox Code Playgroud)
你基本上可以这样做:
int[] ints = new[] { 10, 20, 10, 34, 113 };
Run Code Online (Sandbox Code Playgroud)
这是你的数组,然后你可以像这样调用你的新列表:
var newList = new List<int>(ints);
Run Code Online (Sandbox Code Playgroud)
您也可以对复杂对象执行此操作。
| 归档时间: |
|
| 查看次数: |
461921 次 |
| 最近记录: |