Prepend method in LINQ
Yesterday I needed to put one element at beginning of the collection I already had. Some kind of Concat upside down. 😃 As you can use the Concat method, it looks weird when you see the code, because two items are actually swapped. So I created a simple extension method to do it for me.
I started with:
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
yield return item;
foreach (var x in source)
yield return x;
}
It’s classic imperative approach, you’re expressing how you’ll do it. Then I thought: “Hey, why not to use LINQ methods already available.". As you guess, I abused Concat method as I wrote above:
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
return new[] { item }.Concat(source);
}
You can easily extend both methods to accept also collection as a second parameter.
If you’re more about declarative programming you’ll probably like the other one. But choose whatever fits your brain better.