we all know the slow way:
foreach..
we all know the slow way:
foreach..
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.)
The List constructor is a good bet.
IEnumerable<T> enumerable = ...;
List<T> list = new List<T>(enumerable);
You want to use the .AddRange method on generic List.
List<string> strings = new List<string>();
strings.AddRange(...);
.. or the constructor ..
new List<string>(...);