How can I generate random alphanumeric strings?

后端 未结 30 3536
予麋鹿
予麋鹿 2020-11-22 03:17

How can I generate a random 8 character alphanumeric string in C#?

30条回答
  •  青春惊慌失措
    2020-11-22 03:49

    Question: Why should I waste my time using Enumerable.Range instead of typing in "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Test
    {
        public static void Main()
        {
            var randomCharacters = GetRandomCharacters(8, true);
            Console.WriteLine(new string(randomCharacters.ToArray()));
        }
    
        private static List getAvailableRandomCharacters(bool includeLowerCase)
        {
            var integers = Enumerable.Empty();
            integers = integers.Concat(Enumerable.Range('A', 26));
            integers = integers.Concat(Enumerable.Range('0', 10));
    
            if ( includeLowerCase )
                integers = integers.Concat(Enumerable.Range('a', 26));
    
            return integers.Select(i => (char)i).ToList();
        }
    
        public static IEnumerable GetRandomCharacters(int count, bool includeLowerCase)
        {
            var characters = getAvailableRandomCharacters(includeLowerCase);
            var random = new Random();
            var result = Enumerable.Range(0, count)
                .Select(_ => characters[random.Next(characters.Count)]);
    
            return result;
        }
    }
    

    Answer: Magic strings are BAD. Did ANYONE notice there was no "I" in my string at the top? My mother taught me not to use magic strings for this very reason...

    n.b. 1: As many others like @dtb said, don't use System.Random if you need cryptographic security...

    n.b. 2: This answer isn't the most efficient or shortest, but I wanted the space to separate the answer from the question. The purpose of my answer is more to warn against magic strings than to provide a fancy innovative answer.

提交回复
热议问题