Is there a statement to prepend an element T to a IEnumerable<T>

I take it you can't just Insert into the existing list?

Well, you could use new[] {element}.Concat(list).

Otherwise, you could write your own extension method:

    public static IEnumerable<T> Prepend<T>(
            this IEnumerable<T> values, T value) {
        yield return value;
        foreach (T item in values) {
            yield return item;
        }
    }
    ...

    var singleList = list.Prepend("a");

Since .NET framework 4.7.1 there is LINQ method for that:

list.Prepend("a");

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend?view=netframework-4.7.1


You can roll your own:

static IEnumerable<T> Prepend<T>(this IEnumerable<T> seq, T val) {
 yield return val;
 foreach (T t in seq) {
  yield return t;
 }
}

And then use it:

IEnumerable<string> singleList = list.Prepend(element);

Tags:

C#

Linq