C# array to list

I do not want to make a loop to go from array to list.
ToList() does not work
new List<object>(myArray) does not work
List<object> list = myArray.ToList<object>(); does not work
ConvertAll is not clear to me

Do you know what the right code is?

question8.gh (4.9 KB)

Include: using System.Linq; and try all again.

1 Like

You can construct a list directly from an array, but it requires your list and array have the same type constraint. So:

var array = new int[] { 1, 2, 3 };
var list = new List<int>(array);

will work just fine. Whereas:

var array = new object[] { 1, 2, 3 };
var list = new List<int>(array);

will not. object is more general than int, so the compiler doesn’t allow you to use it, even if the object array only contains integers. See, the compiler doesn’t care about the specific runtime case, it cares about whether the code is type-correct.

1 Like