C# 创建重复元素的 List<T> 的最短方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1120723/
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-06 08:41:24  来源:igfitidea点击:

Shortest way to create a List<T> of a repeated element

c#.net.net-3.5list

提问by xyz

With the String class, you can do:

使用 String 类,您可以执行以下操作:

string text = new string('x', 5);
//text is "xxxxx"

What's the shortest way to create a List< T > that is full of nelements which are all the same reference?

创建一个充满n相同引用元素的 List< T > 的最短方法是什么?

采纳答案by JaredPar

Try the following

尝试以下

var l = Enumerable.Repeat('x',5).ToList();

回答by Andy_Vulhop

Fastest way I know is:

我知道的最快方法是:

int i = 0;
MyObject obj = new MyObeject();
List<MyObject> list = new List<MyObject>();
for(i=0; i< 5; i++)
{
    list.Add(obj);
}

which you can make an extention method if you want to use it multiple times.

如果您想多次使用它,您可以制作一个扩展方法。

public void AddMultiple(this List<T> list, T obj, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        list.Add(obj);
    }
}

Then you can just do:

然后你可以这样做:

List<MyObject> list = new List<MyObject>();
MyObject obj = new MyObject();
list.AddMultiple(obj, 5);

回答by JP Alioto

This seems pretty straight-forward ...

这看起来很简单......

for( int i = 0; i < n; i++ ) { lst.Add( thingToAdd ); }

:D

:D