Extension method for Enumerable.Intersperse?

前端 未结 5 1759
被撕碎了的回忆
被撕碎了的回忆 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:24

    I've coded up a solution that is lazy, in the spirit of Linq solutions! Other solutions I came up with involved traversing the entire list before returning data, and then returning the resulting list.

    Some of the other answers have an if check on every iteration of the loop.

    public static IEnumerable Intersperse(this IEnumerable source, T element)
    {
        using (var enumerator = source.GetEnumerator()) {
            if (enumerator.MoveNext()) {
                yield return enumerator.Current;
                while (enumerator.MoveNext()) {
                    yield return element;
                    yield return enumerator.Current;
                }
            }
        }
    }
    

提交回复
热议问题