Enumerable.Append and Enumerable.Prepend extension methods

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

I never fully recovered my workspace setup when I upgraded my laptop two years ago, and I still miss things today. If only I had known about Gitpod back then…

Learn more

Another gem I found on StackOverflow today (I’ve been spending a lot of time there these last couple of days..), this time in the form of a question on how to append or prepend a single value to an IEnumerable<T>.

Greg provided an elegant solution to this particular problem, 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 others have stated, what’s so nice about this solution is that it does not mutate the original collection, instead it generates a new IEnumerbale<T>.

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

Leave a Comment

Your email address will not be published. Required fields are marked *