-1

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.

2 Answers2

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.

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
  • 7,259
  • 2
  • 7
  • 21
  • I'd go as far as requiring a signature like `List Contcat(List strings, int quantity)` because resizing an array can become very expensive, very fast. – Austin T French Apr 08 '21 at 16:28
  • 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