ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

ToList(capacity)

LINQ ToList() extension method with an extra capacity argument. This can boost the speed of creating the list.

Source

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source, int capacity) {
    if (source == null) {
        throw new ArgumentNullException(nameof(source));
    }
    if (capacity < 0) {
        throw new ArgumentOutOfRangeException(nameof(capacity), "Non-negative number required.");
    }
    var list = new List<TSource>(capacity);
    list.AddRange(source);
    return list;
}

Example

IEnumerable<string> data = GetData();
var l = data.ToList(100000);

Console.WriteLine(l.Count);
Console.WriteLine(l.Capacity);

Author: Fons Sonnemans

Submitted on: 3 apr 2017

Language: csharp

Type: ienumerable-t

Views: 4218