简体   繁体   中英

C# How to best add elements of string array to generic List

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM