score:13

Accepted answer

If you don't care which characters then you could just use the String constructor:

String s = new String('0', 500);

This will give you a string with 500 "0"s. Or for 500 X's:

String s = new String('X', 500);

score:1

This should do the trick.

var range = new string(String.Concat(Enumerable.Range(0, 500)
                                               .Select(c => c.ToString()))
                             .Take(500).ToArray()
                      );

score:1

LINQ is nifty, but you don't always need it...:

static string NumString(int length) {
    var s = "";
    var i = 0;
    while (s.Length < length) {
        s += i.ToString();
        i++;
    }
    return s.Substring(0, length);
}

Or a variant using Aggregate:

var str = Enumerable.Range(0, 500)
          .Aggregate("", (s, next) => s += next.ToString(), 
                         s => s.Substring(0, 500));

score:2

You want to use Aggregate:

  string range = Enumerable.Range(0,500)
                .Select(x => x.ToString()).Aggregate((a, b) => a + b);
  Console.WriteLine(range);

This will give you a string of concatenated numbers from 0 to 500. Like this: 01234567891011121314151617...
if you need to take 500 chars from this big string, you can further use substring.

string range = Enumerable.Range(0,500)
              .Select(x => x.ToString()).Aggregate((a, b) => a + b);
Console.WriteLine(range.Substring(0, 500));

score:0

new string(Enumerable.Range(0,500).SelectMany(x => x.ToString()).Take(500).ToArray())

Simplest way with LINQ. Since a string is technically an enumerable (char[]), you can use SelectMany (which takes multiple Enumerables and flattens into a single collection) followed by a Take(500) to only get 500 characters, call ToArray to get a char[] to instantiate a new string.

score:0

One more option, not quite the requested output from the original question - digits are random rather than increasing - but fairly succinct (I know, the OP didn't require a string of random digits but here's one in any case).

var rand = new Random();
string.Join("",Enumerable.Repeat(0, 500).Select(i => rand.Next(10)));

Related Articles