469,266 Members | 1,909 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,266 developers. It's quick & easy.

copy array to List

What is the most performant way to copy an array's elements into a List ?
Jan 4 '07 #1
3 90760
"John Grandy" <johnagrandy-at-gmail-dot-comwrote in message
news:OE**************@TK2MSFTNGP04.phx.gbl...
What is the most performant way to copy an array's elements into a List ?
string[] astrTest = new string[5];

astrTest[0] = "One";

astrTest[1] = "One";

astrTest[2] = "One";

astrTest[3] = "One";

astrTest[4] = "One";

List<stringlstTest = new List<string>(astrTest);
Jan 4 '07 #2
"John Grandy" <johnagrandy-at-gmail-dot-comwrote:
What is the most performant way to copy an array's elements into a List ?
I always use the .AddRange() method on List<T>. I've never profiled it to
see if there's a faster way, but I would think not.

Certainly, this is the best method in terms of Code Clarity and Maintenance,
which are generally way more important than the actual performance.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, MVP C#
http://www.coversant.net/blogs/cmullins
Jan 5 '07 #3
"Chris Mullins [MVP]" <cm******@yahoo.comwrote
"John Grandy" <johnagrandy-at-gmail-dot-comwrote:
>What is the most performant way to copy an array's elements into a List ?

I always use the .AddRange() method on List<T>. I've never profiled it to
see if there's a faster way, but I would think not.

Certainly, this is the best method in terms of Code Clarity and
Maintenance, which are generally way more important than the actual
performance.
I should add that, if it's practical, you should allocate your List<Twith
the correct capacity.

This means if you have a populated array myArray, you should:

List<stringmyList = new List<string>(myArray.Length);
myList.AddRange(myArray);

Doing this will avoid all sorts of unnecessary memory allocations and array
resizes.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, MVP C#
http://www.coversant.net/blogs/cmullins
Jan 5 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by sam | last post: by
4 posts views Thread by jonny | last post: by
1 post views Thread by Phenix Smith | last post: by
13 posts views Thread by Hrvoje Voda | last post: by
11 posts views Thread by Zorpiedoman | last post: by
18 posts views Thread by Doug Bell | last post: by
2 posts views Thread by Brian Pelton | last post: by
3 posts views Thread by Ant | last post: by
22 posts views Thread by Energizer100 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.