Shortest way to create a List of a repeated element

前端 未结 3 728
野性不改
野性不改 2021-02-06 21:36

With the String class, you can do:

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

What\'s the shortest way to create a List< T > th

3条回答
  •  走了就别回头了
    2021-02-06 22:06

    Fastest way I know is:

    int i = 0;
    MyObject obj = new MyObeject();
    List list = new List();
    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 list, T obj, int n)
    {
        int i;
        for(i=0;i

    Then you can just do:

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

提交回复
热议问题