[英]How to repeat n values in list m times in C#?
For example, I have a list例如,我有一个列表
var list = new List<int> { 1, 2, 3 };
and I want to repeat its content 3 times to get in result我想重复其内容 3 次以获得结果
{ 1, 2, 3, 1, 2, 3, 1, 2, 3 }
Is there a simpler solution than just AddRange
m times in for loop?有没有比 for 循环中的
AddRange
m 次更简单的解决方案?
using Enumerable.Repeat
使用
Enumerable.Repeat
var repeatCount = 3; //change this value to repeat n times
var list = new List<int> { 1, 2, 3 };
var result = Enumerable.Repeat(list, repeatCount).SelectMany(x => x).ToList();
You can use LINQ's Enumerable.Range
with SelectMany
:您可以将 LINQ 的
Enumerable.Range
与SelectMany
一起使用:
list = Enumerable.Range(0, 3)
.SelectMany(_ => list)
.ToList();
This will differ from adding to the list though - new list will be created here.这将不同于添加到列表中 - 将在此处创建新列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.