Reputation: 21226
I want to generate 500 chars in an easy way without doing:
String range = "0123456789101112131415...";
I want to have an exact string of 500 chars.
How can I do that?
Enumerable.Range(0,500).Select( c => c.ToString());
does not help because
the number 123 is 3 chars not 1 and therein is the problem.
Upvotes: 3
Views: 3138
Reputation: 13266
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)));
Upvotes: 0
Reputation: 3892
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.
Upvotes: 0
Reputation: 13235
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));
Upvotes: 1
Reputation: 3395
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));
Upvotes: 2
Reputation: 116188
This should do the trick.
var range = new string(String.Concat(Enumerable.Range(0, 500)
.Select(c => c.ToString()))
.Take(500).ToArray()
);
Upvotes: 1
Reputation: 7911
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);
Upvotes: 13