Enumerable.Prepend Method

Namespace: System.Linq

Assembly: System.Linq.dll

Applies to: .NET Framework, .NET Core, .NET 5+

Description: Appends an element to the beginning of a sequence.

Syntax

public static IEnumerable<TSource> Prepend<TSource>( IEnumerable<TSource> source, TSource element );

Parameters

source: IEnumerable<TSource>
The sequence to prepend an element to.
element: TSource
The element to prepend to the sequence.

Returns

An IEnumerable<TSource> that contains the specified element at the beginning of the sequence, followed by the elements of the original sequence.

Remarks

The Prepend method returns an enumerable collection that first contains the specified element and then contains all elements in the original source sequence.

This method does not return an eagerly evaluated collection. The elements are not retrieved until the enumerable collection is iterated over.

If source is null, a ArgumentNullException is thrown.

Example

The following code example demonstrates how to use the Prepend method to add an element to the beginning of a list.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main()
    {
        List<string> fruits = new List<string> { "Banana", "Orange", "Apple" };

        // Prepend "Mango" to the list
        IEnumerable<string> newFruits = fruits.Prepend("Mango");

        Console.WriteLine("Original list:");
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("\nList after Prepend:");
        foreach (var fruit in newFruits)
        {
            Console.WriteLine(fruit);
        }
    }
}

Output:


Original list:
Banana
Orange
Apple

List after Prepend:
Mango
Banana
Orange
Apple

See Also

Enumerable Class

Enumerable.Append Method

System.Linq Namespace