ExtensionMethod.NET Home of 820 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);
    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);

Author: Fons Sonnemans

Submitted on: 3 apr 2017

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 2040