Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can create N items of a specific element in c#?

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 ?,?,?,?
  • EDIT 1

I am looking in a simple way. Probably using 1-2 line of code. In c++ there are array fill() and joins.

  • EDIT 2

I need this for Compact Framework

like image 259
Pentium10 Avatar asked Feb 12 '10 15:02

Pentium10


3 Answers

Use the new Enumerable.Repeat method in conjunction with String.Join:

String.Join(sep, Enumerable.Repeat(element, n).ToArray());
like image 198
Jon Benedicto Avatar answered Oct 16 '22 10:10

Jon Benedicto


var result = Enumerable.Repeat(element, n).DefaultIfEmpty("").Aggregate((s1, s2) => s1 + sep + s2);
like image 20
Mark Seemann Avatar answered Oct 16 '22 11:10

Mark Seemann


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.

like image 41
Kevin Gale Avatar answered Oct 16 '22 10:10

Kevin Gale