6

If I have an array of strings such as:

string[] strArr = {"First", "Second", "Third"};

...and I want to add these to a generic List

List<string> strList = new List<string>();

what is the best way to go about it?

Option 1: Loop with for or foreach, using .Add method.

Option 2: .AddRange method (ref example on MSDN here):

strList.AddRange = new List<string>(strArr);

Or other options?

0

1 Answer 1

7

Use the constructor that takes an IEnumerable:

List<string> strList = new List<string>(strArr);

or call ToList() on your array:

List<string> strList = strArr.ToList();

which is probably the most common way to do it.

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

2 Comments

i do not see the method array.ToList() learn.microsoft.com/en-us/dotnet/api/system.array?view=net-5.0 It also gets flagged as an error . new List<string>(ary) does work
ToList() is an extension off IEnumerable<T> from System.Linq namespace

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.