Extension method for Enumerable.Intersperse?
I've coded up a solution that is lazy, in the spirit of Linq solutions! Other solutions I came up with involved traversing the entire list before returning data, and then returning the resulting list.
Some of the other answers have an if check on every iteration of the loop.
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
using (var enumerator = source.GetEnumerator()) {
if (enumerator.MoveNext()) {
yield return enumerator.Current;
while (enumerator.MoveNext()) {
yield return element;
yield return enumerator.Current;
}
}
}
}
Something the others have missed: if you only want it in between items, and not also in front or behind, you need to do an extra check:
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
bool first = true;
foreach (T value in source)
{
if (!first) yield return element;
yield return value;
first = false;
}
}
or
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
var e = source.GetEnumerator();
bool b = e.MoveNext();
if (b) yield return e.Current;
while (e.MoveNext())
{
yield return element;
yield return e.Current;
}
}
It would be pretty easy to write:
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T value) {
bool first = true;
foreach(T item in source) {
if(first) { first = false; }
else { yield return value; }
yield return item;
}
}