C#多次重复IEnumerable

m0n*_*awk 2 c# ienumerable

如何重复整体 IEnumerable多次?

与Python类似:

> print ['x', 'y'] * 3
['x', 'y', 'x', 'y', 'x', 'y']
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

您可以使用普通LINQ来执行此操作:

var repeated = Enumerable.Repeat(original, 3)
                         .SelectMany(x => x);
Run Code Online (Sandbox Code Playgroud)

或者你可以写一个扩展方法:

public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source,
                                       int count)
{
    for (int i = 0; i < count; i++)
    {
        foreach (var item in source)
        {
            yield return count;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在这两种情况下,序列都会在每个"重复"上重新评估 - 因此它可能会给出不同的结果,甚至是不同的长度......实际上,某些序列的评估不能超过一次.你需要小心你做的事情,基本上:

  • 如果您知道序列只能被评估一次(或者您希望从不一致的序列获得一致的结果)但是您很乐意将评估结果缓冲到内存中,则可以ToList()先调用并调用Repeat
  • 如果您知道序列可以连续多次评估,请Repeat按上述方式调用
  • 如果您处于上述两种情况中,则根本无法多次重复序列元素