Function to generate random alphanumeric characters

Asked

Viewed 7,864 times

8

I need a C# function that manages a String of random alphabetic and numerical characters of size N.

1 answer

11


Follows the function that receives as parameter the amount of return characters, and returns a string.

public static string alfanumericoAleatorio(int tamanho)
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var result = new string(
        Enumerable.Repeat(chars, tamanho)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
    return result;
}

Is used Enumerable.Repeat which serves to manage a sequence containing a repeated value, which takes two parameters, the first is the value to be repeated and the second is the number of times it repeats.

Then the method is used Select of LINQ, iterating to each line and using the expression random.Nextwhich receives as a parameter a int32 representing the maximum return number.

Within the select has the expression s => s[random.Next(s.Length)] , in the case s is a line with that content = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" random.Next(s.Length) will generate a random number by taking a character from string, where s.Length is the total character size of the string.

.ToArray() places all returned characters in a character array.

new string() turns this character array into a string.

  • 4

    I think it would be good to at least explain the code, otherwise the question/answer is a little weird for me. The interesting part of sharing is not the tool but in this case, here at Sopt, is how to make the tool.

  • I’ll edit the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.