How can I generate random alphanumeric strings?

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

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

30条回答
  •  暖寄归人
    2020-11-22 04:04

    I don't know how cryptographically sound this is, but it's more readable and concise than the more intricate solutions by far (imo), and it should be more "random" than System.Random-based solutions.

    return alphabet
        .OrderBy(c => Guid.NewGuid())
        .Take(strLength)
        .Aggregate(
            new StringBuilder(),
            (builder, c) => builder.Append(c))
        .ToString();
    

    I can't decide if I think this version or the next one is "prettier", but they give the exact same results:

    return new string(alphabet
        .OrderBy(o => Guid.NewGuid())
        .Take(strLength)
        .ToArray());
    

    Granted, it isn't optimized for speed, so if it's mission critical to generate millions of random strings every second, try another one!

    NOTE: This solution doesn't allow for repetitions of symbols in the alphabet, and the alphabet MUST be of equal or greater size than the output string, making this approach less desirable in some circumstances, it all depends on your use-case.

提交回复
热议问题