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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:45:23  来源:igfitidea点击:

Add one item multiple times to same List

c#collections

提问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

You can use Repeat:

您可以使用Repeat

List<int> listFullOfInts = Enumerable.Repeat(42, 50).ToList();

Demo

演示

If you already have a list and you don't want to create a new one with ToList:

如果您已经有一个列表并且您不想创建一个新的列表ToList

listFullOfInts.AddRange(Enumerable.Repeat(42, 50));

回答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);