How to initialize List<> with array? Like:
List<string> list = new List<string>();
string[] str = new string[5];
list = str;
How to initialize List<> with array? Like:
List<string> list = new List<string>();
string[] str = new string[5];
list = str;
There is a constructor of List which takes an IEnumerable (which an array implements)
string[] myArray = new string[5];
List<string> myList = new List<string>(myArray);
https://msdn.microsoft.com/en-us/library/fkbw11z0(v=vs.100).aspx
Another form, which can only be used if you are declaring the 'array' elements at the same time that you are initializing the list, would be using the collection initializer.
Strictly speaking this does not use an existing array to initialize the list. But in some situations, this would be an advantage, i.e. you don't have to also declare, nor allocate memory, for a separate array variable.
I personally like this form because of its conciseness.
// several examples (note: no separate array is declared during initialization
// of the list)
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 }
};
List<Cat?> moreCats = new List<Cat?>
{
new Cat{ Name = "Peaches", Age=4 },
null
};
var numbers = new Dictionary<int, string>
{
[7] = "seven",
[9] = "nine",
};