Extension method for Enumerable.Intersperse?

前端 未结 5 1760
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 16:27

I learned the intersperse function from Haskell, and have been looking for an implementation in c#.

Intersperse takes 2 arguments, an IEnumerable source and

5条回答
  •  一个人的身影
    2020-12-11 17:23

    It would be pretty easy to write:

    public static IEnumerable Intersperse(this IEnumerable source, T value) {
        bool first = true;
        foreach(T item in source) {
             if(first) { first = false; }
             else { yield return value; }
             yield return item;
        }
    }
    

提交回复
热议问题