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

Append() and Prepend()

Append() adds a value to the end of the sequence. Prepend() adds a value to the beginning of the sequence. This is usefull if you are not using .NET Core or .NET Framework 4.7.

Source

public static class Enumerable {

    /// <summary>
    /// Appends a value to the end of the sequence. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">A sequence of values.</param>
    /// <param name="element">The value to append to source.</param>
    /// <returns>A new sequence that ends with element.</returns>
    public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T element) {
        foreach (var item in source) {
            yield return item;
        }
        yield return element;
    }

    /// <summary>
    /// Adds a value to the beginning of the sequence.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">A sequence of values.</param>
    /// <param name="element">The value to prepend to source.</param>
    /// <returns>A new sequence that begins with element</returns>
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T element) {
        yield return element;
        foreach (var item in source) {
            yield return item;
        }
    }

}

Example

var numbers = new int[] { 1, 2, 3, 4 };
var qry = numbers.Append(5).Append(6).Prepend(0);
foreach (var item in qry) {
    Console.WriteLine(item);
}
// Outputs: 0, 1, 2, 3, 4, 5, 6

Author: Fons Sonnemans

Submitted on: 21 jun 2018

Language: C#

Type: IEnumerableOfT

Views: 6150