8

I want to create a string repeating the same seqeuence n-times.

How I do this:

var sequence = "\t";
var indent = string.Empty;   

for (var i = 0; i < n; i++)
{
    indent += sequence;
}

Is there a neat LINQ equivalent to accomplish the same result?

boop
  • 7,413
  • 13
  • 50
  • 94
  • [repeat string with LINQ/extensions methods](https://stackoverflow.com/q/13864493/150605) is very similar but seeks to repeat `string`s, not `char`s. [Best way to repeat a character in C#](https://stackoverflow.com/q/411752/150605) is identical as far as seeking to create a `string` of tab characters, and though it isn't restricted to LINQ, does contain many LINQ/`Enumerable` answers. – Lance U. Matthews Aug 07 '19 at 16:42

1 Answers1

9

You can use Enumerable.Repeat in String.Concat:

string intend = String.Concat(Enumerable.Repeat(sequence, n));

If you just want to repeat a single character you should prefer the String-constructor:

string intend = new String('\t', n);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @boop Not relevant for your sample code, but if you are using a StringBuilder, there is also a method .Append('\t', n). – Rob Aug 07 '19 at 16:36
  • 1
    I recommend `string.Join(sequence, new string[n + 1])` to avoid the StringBuilder overhead – Slai Aug 07 '19 at 16:57