简体   繁体   English

如何在C#中将数组转换为List <object>?

[英]How do I convert an Array to a List<object> in C#?

如何在C#中将Array转换为List<object>

List<object> list = myArray.Cast<Object>().ToList();

如果数组元素的类型是引用类型,则可以.Cast<object>()因为C#4添加了接口协方差,即IEnumerable<SomeClass>可以被视为IEnumerable<object>

List<object> list = myArray.ToList<object>();

使用构造函数: new List<object>(myArray)

List<object>.AddRange(object[]) should do the trick. List<object>.AddRange(object[])应该可以解决问题。 It will avoid all sorts of useless memory allocation. 它将避免各种无用的内存分配。 You could also use Linq, somewhat like this: object[].Cast<object>().ToList() 你也可以使用Linq,有点像这样: object[].Cast<object>().ToList()

The List<> constructor can accept anything which implements IEnumerable, therefore... List <>构造函数可以接受任何实现IEnumerable的东西,因此......

        object[] testArray = new object[] { "blah", "blah2" };
        List<object> testList = new List<object>(testArray);
private List<object> ConvertArrayToList(object[] array)
{
  List<object> list = new List<object>();

  foreach(object obj in array)
    list.add(obj);

  return list;
}

如果数组项和列表项相同

List<object> list=myArray.ToList();

Everything everyone is saying is correct so, 每个人都说的一切都是正确的,所以,

int[] aArray = {1,2,3};
List<int> list = aArray.OfType<int> ().ToList();

would turn aArray into a list, list. 将aArray变成列表,列表。 However the biggest thing that is missing from a lot of comments is that you need to have these 2 using statements at the top of your class 然而,许多评论中遗漏的最大问题是你需要在你的班级顶部使用这两个使用语句

using System.Collections.Generic;
using System.Linq;

I hope this helps! 我希望这有帮助!

您还可以直接使用数组初始化列表:

List<int> mylist= new List<int>(new int[]{6, 1, -5, 4, -2, -3, 9});

其他方式

List<YourClass> list = (arrayList.ToArray() as YourClass[]).ToList();

这允许您发送一个对象:

private List<object> ConvertArrayToList(dynamic array)

Here is my version: 这是我的版本:

  List<object> list = new List<object>(new object[]{ "test", 0, "hello", 1, "world" });

  foreach(var x in list)
  {
      Console.WriteLine("x: {0}", x);
  }

You can try this, 你可以试试这个,

using System.Linq;
string[] arrString = { "A", "B", "C"};
List<string> listofString = arrString.OfType<string>().ToList();

Hope, this code helps you. 希望,这段代码可以帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM