Intersperse implementation in C#

By FoxLearn 11/9/2024 12:59:03 PM   63
In this post, I'll demonstrate how to implement an Intersperse method in C# as an extension method on the IEnumerable<T> interface.

I used `yield` to minimize unnecessary iterations over the collection, reducing overhead. While I could have used a method like `Zip`, it would have introduced more complexity, requiring additional manipulation of the sequence. The `yield`-based approach is simpler and more efficient for this task.

public static class EnumerableExtensions
{
    public static IEnumerable<T> Intersperse<T>(this IEnumerable<T>? source, T delimiter)
    {
        if (source is null) yield break;
        using var enumerator = source.GetEnumerator();
        var hasFirstElement = enumerator.MoveNext();
        if (hasFirstElement == false) yield break;
        yield return enumerator.Current;

        while (enumerator.MoveNext())
        {
            yield return delimiter;
            yield return enumerator.Current;
        }
    }
}

Usage

var text = new string("FoxLearn".Intersperse('-').ToArray()); // F-o-x-L-e-a-r-n
var number = new string("100".Intersperse('x').ToArray()); // 1x0x0
var array = new[] { 1, 2, 3 }.Intersperse(10).ToArray(); // 1, 10, 2, 10, 3
var menus = new[] { "Home", "About", "Privacy" } // Home > About > Privacy
    .Intersperse(" > ")
    .Aggregate((a, b) => $"{a}{b}");