开发者

Whats a quick way to convert an IEnumerable<Foo> to List<Foo> in C# 2.0?

we all know the slow way:

foreach..开发者_Go百科


The List constructor is a good bet.

IEnumerable<T> enumerable = ...;
List<T> list = new List<T>(enumerable);


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.)


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

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

.. or the constructor ..

new List<string>(...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜