So I know in Python you can have
thislist = ["apple", "banana", "cherry"] + ['taco'] *2
which will print out ['apple', 'banana', 'cherry', 'taco', 'taco']
. Is there something similar in c# that can be used? I am writing a list and will have 20-30 of the same item in the list and I just want to save myself some work and possibly make it look clean.
Asked
Active
Viewed 66 times
-1

lunar soap5
- 11
- 3
-
Is there a rule to determine which items in the list are to be repeated? – Peter Smith Apr 08 '21 at 16:05
-
This question needs details or clarity – Serge Apr 09 '21 at 13:07
2 Answers
3
Is not similar as Python but you could use:
List<string> strList = new List<string>();
strList.AddRange(Enumerable.Repeat("Hello", 50));
This will add "Hello" 50 times.

Isaac Caparrós Gónzalez
- 115
- 6
-
I am wondering how it can result ['apple', 'banana', 'cherry', 'taco', 'taco']? – Serge Apr 09 '21 at 13:07
1
Try this (it is just a tip)
var x=["apple", "banana", "cherry"];
var y= MultArray("taco",2);
var result=ConcatArrays(x,y);
To create array of the same strings:
public static string[] MultArray(string str, int quantity)
{
var z = new string[quantity];
for(i=0, i<quantity, i++)
{
z[i]=str;
}
return z;
}
to concat
public static string[] ConcatArrays(string[] x, string[] y)
{
var z = new string[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
return z;
}
I believe you can create a generic function if you have a lot of arrays.
Another way is to convert arrays to list and use the list functions. In the end you will have to convert a list to array. But it is much more expensive.

Serge
- 40,935
- 4
- 18
- 45
-
I'd go as far as requiring a signature like `List
Contcat(List – Austin T French Apr 08 '21 at 16:28strings, int quantity)` because resizing an array can become very expensive, very fast. -
Sorry, but each Add to resize list is much more expensive. Since list uses array under hood. – Serge Apr 08 '21 at 16:31
-
I don't know why you say that. I've never tested it myself, but the general consensus is that resizing a List is faster: https://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which and https://stackoverflow.com/questions/454916/performance-of-arrays-vs-lists Regardless, I feel I need to look closer myself. – Austin T French Apr 09 '21 at 12:59