昨晚我做了一个梦,下面的事情是不可能的。但在同一个梦里,有人告诉我事实并非如此。因此,我想知道是否有可能转换系统。数组到列表

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);

to

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

当前回答

有趣的是,没有人回答这个问题,OP使用的不是强类型int[],而是数组。

你必须强制转换数组为它实际上是什么,int[],然后你可以使用ToList:

List<int> intList = ((int[])ints).ToList();

注意Enumerable。ToList调用列表构造函数,该构造函数首先检查参数是否可以强制转换为ICollection<T>(这是数组实现的),然后它将使用更有效的ICollection<T>。方法,而不是枚举序列。

其他回答

你可以试试你的代码:

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);

int[] anyVariable=(int[])ints;

然后你可以使用anyVariable作为你的代码。

在vb.net中这样做

mylist.addrange(intsArray)

or

Dim mylist As New List(Of Integer)(intsArray)

只需使用现有的方法.. tolist ();

   List<int> listArray = array.ToList();

亲吻(简单点,先生)

你可以这样做:

int[] ints = new[] { 10, 20, 10, 34, 113 };

这是你的数组,然后你可以像这样调用你的新列表:

 var newList = new List<int>(ints);

你也可以对复杂对象这么做。

在希望以列表形式返回枚举数组的情况下,可以执行以下操作。

using System.Linq;

public List<DayOfWeek> DaysOfWeek
{
  get
  {
    return Enum.GetValues(typeof(DayOfWeek))
               .OfType<DayOfWeek>()
               .ToList();
  }
}