How do I convert an Array to a List<object> in C#?
C#ArraysC# Problem Overview
How do I convert an Array
to a List<object>
in C#?
C# Solutions
Solution 1 - C#
List<object> list = myArray.Cast<Object>().ToList();
If the type of the array elements is a reference type, you can leave out the .Cast<object>()
since C#4 added interface co-variance i.e. an IEnumerable<SomeClass>
can be treated as an IEnumerable<object>
.
List<object> list = myArray.ToList<object>();
Solution 2 - C#
Use the constructor: new List<object>(myArray)
Solution 3 - C#
List<object>.AddRange(object[])
should do the trick. It will avoid all sorts of useless memory allocation.
You could also use Linq, somewhat like this: object[].Cast<object>().ToList()
Solution 4 - C#
The List<> constructor can accept anything which implements IEnumerable, therefore...
object[] testArray = new object[] { "blah", "blah2" };
List<object> testList = new List<object>(testArray);
Solution 5 - C#
private List<object> ConvertArrayToList(object[] array)
{
List<object> list = new List<object>();
foreach(object obj in array)
list.add(obj);
return list;
}
Solution 6 - C#
If array item and list item are same
List<object> list=myArray.ToList();
Solution 7 - C#
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. 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!
Solution 8 - C#
You can also initialize the list with an array directly:
List<int> mylist= new List<int>(new int[]{6, 1, -5, 4, -2, -3, 9});
Solution 9 - C#
another way
List<YourClass> list = (arrayList.ToArray() as YourClass[]).ToList();
Solution 10 - C#
This allow you to send an object:
private List<object> ConvertArrayToList(dynamic array)
Solution 11 - C#
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);
}
Solution 12 - C#
You can try this,
using System.Linq;
string[] arrString = { "A", "B", "C"};
List<string> listofString = arrString.OfType<string>().ToList();
Hope, this code helps you.