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.
An IEnumerable<TSource> that contains the specified element at the beginning of the sequence, followed by the elements of the original sequence.
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.
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);
}
}
}
Original list:
Banana
Orange
Apple
List after Prepend:
Mango
Banana
Orange
Apple