如何重复整体 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按上述方式调用