TBAG TBAG - 16 days ago 5
C# Question

Random iteration in loop for printing characters present in list randomly

I have to loop through number 0-9 and characters A-Z but I want to loop through each element but randomly. I have tried below approach. Is there any better approach you can suggest.

static void Main(string[] args)
{
Random r = new Random();
var listOfAsciiForNumbers = Enumerable.Range(48, 10).ToList();
var listofAsciiForAlphabets = Enumerable.Range(65, 26).ToList();

var asciiList = new List<int>();
asciiList.AddRange(listOfAsciiForNumbers);
asciiList.AddRange(listofAsciiForAlphabets);

foreach (int i in asciiList.OrderBy(x => r.Next()))
{
Console.WriteLine((char)i);
}
}

Answer

Does this work for you?

Random r = new Random();

var ascii =
    Enumerable
        .Concat(
            Enumerable.Range(48, 10),
            Enumerable.Range(65, 26))
        .Select(n => (char)n)
        .OrderBy(c => r.Next());

Console.WriteLine(String.Join(Environment.NewLine, ascii));

Or more tersely:

var ascii =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        .OrderBy(c => r.Next());

Or even:

Console.WriteLine(
    String.Join(
        Environment.NewLine,
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".OrderBy(c => r.Next())));