循环中的随机迭代,用于随机打印列表中的字符

时间:2016-11-24 13:03:27

标签: c# loops random foreach

我必须遍历数字0-9和字符A-Z,但我想循环遍历每个元素但随机。我试过以下方法。有没有更好的方法可以建议。

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);
                }
            }

1 个答案:

答案 0 :(得分:2)

这对你有用吗?

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));

或更简洁:

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

甚至:

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