JavaScript, for better or worse, has a much smaller standard library than what .NET developers are used to with the base class library (BCL). The JavaScript community has made many attempts to build a standard library, and I’m sure some of them are great. As I was scanning the options, I came across a fascinating method named
intersperse
, which “inserts a separator between the elements of its list argument”.
In this post, I’ll implement the same method in C# as an extension method on the IEnumerable
interface.
Intersperse implementation in C#
Let’s first look at a few examples and the expected output before we look at the implementation of the method.
Running this application, we will see the following output.
Let’s get to the implementation!
I used
yield
to reduce the number of iterations on the collection being passed, as it would add unnecessary overhead. Additionally, I could have used a method like
Zip
, but that would have required more gymnastics than the current implementation.
I hope you enjoyed reading this quick blog post, and as always, thanks for reading. Cheers.