I am looking for a way to generate N pieces of question marks joined with comma.
string element="?";
string sep=",";
int n=4;
// code to run and create ?,?,?,?
I am looking in a simple way. Probably using 1-2 line of code. In c++ there are array fill() and joins.
I need this for Compact Framework
Use the new Enumerable.Repeat method in conjunction with String.Join:
String.Join(sep, Enumerable.Repeat(element, n).ToArray());
var result = Enumerable.Repeat(element, n).DefaultIfEmpty("").Aggregate((s1, s2) => s1 + sep + s2);
static string BuildSeparatedString(string element, string sep, int count)
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= count; i++)
{
sb.Append(element);
if (i != count)
sb.Append(sep);
}
return sb.ToString();
}
It's not fancy but neither is it a cryptic one liner. Anyone reading or maintaining the code should very quickly understand it.
By some quick testing this also runs nearly twice as fast as the two most popular one liners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With