ToList(capacity)

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);
    foreach (var item in source) {
        list.Add(item);
    }
    return list;
}
Example:
IEnumerable<string> data = GetData();
var l = data.ToList(100000);

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

Description

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

Details

Double click on the code to select all.

 

;