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}");
- How to handle nulls with SqlDataReader in C#
- Resolve nullable warnings
- Cannot convert null to type parameter ‘T’
- How to create a custom exception in C#
- How to check if a nullable bool is true in C#
- How to make a file read-only in C#
- How to Get all files in a folder in C#
- How to validate an IP address in C#
Categories
Popular Posts
How to disable Windows Defender SmartScreen
12/24/2024