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

FillSpan

Fill any Span using an IEnumerable. Returns the number of items which are placed in the Span.

Source

public static int FillSpan<TSource>(this IEnumerable<TSource> source, Span<TSource> destination) {
    int index = 0;
    foreach (var item in source) {
        if (index >= destination.Length) {
            throw new ArgumentOutOfRangeException(nameof(destination), "Span is too small");
        }
        destination[index++] = item;
    }
    return index;
}

Example

var l = new List<Employee> {
    new Employee("Fons", 2000),
    new Employee("Jim", 4000),
    new Employee("Ellen", 3000),
};

var qry = l.Where(emp => emp.Salary > 2500);

var array = ArrayPool<Employee>.Shared.Rent(200);
try {

    int length = qry.FillSpan(array);

    for (int i = 0; i < length; i++) {
        Console.WriteLine(array[i]);
    }
} finally {
    ArrayPool<Employee>.Shared.Return(array);
}

Author: Fons Sonnemans

Submitted on: 30 nov 2020

Language: csharp

Type: ienumerable-t

Views: 2931