Using Linq for positive integers
var random = new Random();
int count = 5;
int max = (int)Math.Pow(10, count);
int number = random.Next(0, max);
var list = number.ToString(new string('0', count)).Select(c => char.GetNumericValue(c));
var digits = list.ToArray();
Console.WriteLine(number + " => " + string.Join(" ", digits));
Output
32409 => 3 2 4 0 9
123 => 0 0 1 2 3
Explanation
We generate the max value that can fit in the array of count cells (+1).
For count = 5
, we generate numbers between 0..99999
thanks to the Pow
.
We convert it to a string and select each char converted in its numeric value.
The use of new string('0', count)
ensure that we will have 5 digits no matter the generated number: for example 50
will be 00050
and all cells of the array will be filled to match the required size. But if the size of this array may be less than the max count to just have the real digits, it is not needed and will produces:
32409 => 3 2 4 0 9
123 => 1 2 3
To have the expected array we apply the convert method on the resulting query.