对于Enumerable.Intersperse扩展方法? [英] Extension method for Enumerable.Intersperse?
问题描述
我学到了点缀功能< 。/ A>从哈斯克尔,并一直在寻找在C#中实施
I learned the intersperse function from Haskell, and have been looking for an implementation in c#.
中散布需要两个参数,一个IEnumerable< T>源和T元件。它返回一个IEnumerable与源中的每个元素之间插入的元素
Intersperse takes 2 arguments, an IEnumerable<T> source and a T element. It returns an IEnumerable with element inserted between every element of source.
一个可能的用例是把一个任意整数整数列表之间,例如:
One possible use-case is to put an arbitrary integer in between a list of integers, for example:
// returns: {1, 0, 2, 0, 3}
(List<int>() {1, 2, 3}).Intersperse(0);
这是的string.join(...)的一般情况。
This is a general case of string.Join(...).
推荐答案
东西别人已经错过:如果你只希望它在项目之间,不也是在前面还是后面,你需要做额外的检查:
Something the others have missed: if you only want it in between items, and not also in front or behind, you need to do an extra check:
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
bool first = true;
foreach (T value in source)
{
if (!first) yield return element;
yield return value;
first = false;
}
}
这篇关于对于Enumerable.Intersperse扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!