views:

109

answers:

3

we all know the slow way:

foreach..
+5  A: 

How about:

IEnumerable<T> sequence = GetSequenceFromSomewhere();
List<T> list = new List<T>(sequence);

Note that this is optimised for the situation where the sequence happens to be an IList<T> - it then uses IList<T>.CopyTo. It'll still be O(n) in most situations, but potentially a much faster O(n) than iterating :) (It also avoids any resizing as it creates it.)

Jon Skeet
This constructor copies the enumerated items to the new List, so I doubt it's any faster (and nor could it be). But it's certainly easier.
GraemeF
@GraemeF: As I noted, it *is* faster if the sequence happens to be an `IList<T>`.
Jon Skeet
More generically, ICollection<T>'s CopyTo
SwDevMan81
+13  A: 

The List constructor is a good bet.

IEnumerable<T> enumerable = ...;
List<T> list = new List<T>(enumerable);
siz
+2  A: 

You want to use the .AddRange method on generic List.

List<string> strings = new List<string>();
strings.AddRange(...);

.. or the constructor ..

new List<string>(...);
Chad Moran