C# 多次将一项添加到同一个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17169115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add one item multiple times to same List
提问by Sander
What I am trying to achieve is to add one item to a List, multiple times without using a loop.
我想要实现的是在不使用循环的情况下多次将一项添加到列表中。
I am going to add 50 numbers to a List and want all of those number to be equal to, let's say, 42. I am aware that I can simply create a small loop that runs 50 times and adds the same item over and over again, as such;
我将向 List 添加 50 个数字,并希望所有这些数字都等于 42。我知道我可以简单地创建一个运行 50 次的小循环并一遍又一遍地添加相同的项目, 像这样;
List<int> listFullOfInts = new List<int>();
int addThis = 42;
for(int i = 0; i < 50; i++)
listFullOfInts.Add(addThis);
What I am trying to do is something on the lines of;
我正在尝试做的事情是:
listFullOfInts.AddRange(addThis, 50);
Or something that is similar to this at least, maybe using Linq? I have a vague memory of seeing how to do this but am unable to find it. Any ideas?
或者至少与此类似的东西,也许使用 Linq?我对如何执行此操作有模糊的记忆,但无法找到它。有任何想法吗?
采纳答案by Tim Schmelter
回答by Rune FS
You can't do it directly with LINQ since LINQ is side effect free but you can use some of what's found in the System.linq namespace to build the required.
你不能直接用 LINQ 来做,因为 LINQ 没有副作用,但你可以使用 System.linq 命名空间中的一些内容来构建所需的。
public static void AddRepeated<T>(this List<T> self,T item, int count){
var temp = Enumerable.Repeat(item,count);
self.AddRange(temp);
}
you can then use that as you propose in your post
然后您可以按照您在帖子中提出的建议使用它
listFullOfInts.AddRepeated(addThis, 50);

