3

How to initialize List<> with array? Like:

List<string> list = new List<string>();
string[] str = new string[5];
list = str;
1
  • 1
    That is not initialisation, that is assignment. That might seem pedantic, but the difference is very important in programming Commented Dec 6, 2015 at 21:04

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

Pass the array to the List constructor

List<string> list = new List<string>(str);

or use ToList() extension method

List<string> list = str.ToList();

Both of these will create a new List<string> containing elements copied from str.

Comments

-1

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",
};

Using this form requires a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.