
Yan Cui
I help clients go faster for less using serverless technologies.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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:
1 | 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:
- 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.
- 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.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.