Enumerable.Append and Enumerable.Prepend extension methods

Anoth­er gem I found on Stack­Over­flow today (I’ve been spend­ing a lot of time there these last cou­ple of days..), this time in the form of a ques­tion on how to append or prepend a sin­gle val­ue to an IEnumerable<T>.

Greg pro­vid­ed an ele­gant solu­tion to this par­tic­u­lar prob­lem, and here’s his answer:

public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item)
{
    foreach (T i in source)
        yield return i;

    yield return item;
}

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
    yield return item;

    foreach (T i in source)
        yield return i;
}

Which you can use like this:

var all = GetHeaders().Append(GetData());

As oth­ers have stat­ed, what’s so nice about this solu­tion is that it does not mutate the orig­i­nal col­lec­tion, instead it gen­er­ates a new IEnumerbale<T>.