tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Prepend method in LINQ

29 Jun 2010 .NET, C#, 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.

Profile Picture Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.