How do I convert an Array to a List<object> in C#?
Solution 1:
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:
Use the constructor: new List<object>(myArray)
Solution 3:
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:
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:
private List<object> ConvertArrayToList(object[] array)
{
List<object> list = new List<object>();
foreach(object obj in array)
list.add(obj);
return list;
}