I learned the intersperse function from Haskell, and have been looking for an implementation in c#.
Intersperse takes 2 arguments, an IEnumerable
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 Intersperse(this IEnumerable 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;
}
}
}
}