Intersperse implementation in C#
By FoxLearn 11/9/2024 12:59:03 PM 42
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 Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?
- How to retrieve the Downloads Directory Path in C#
- How to implement keyboard shortcuts in a Windows Forms application
- How to get current assembly in C#
Categories
Popular Posts
Material Lite Admin Template
11/14/2024
Freedash bootstrap lite
11/13/2024
RuangAdmin Template
11/17/2024
Responsive Animated Login Form
11/11/2024