Function to generate random alphanumeric characters

7

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

    
asked by anonymous 01.09.2015 / 21:38

1 answer

10

Here is the function that receives the number of return characters as a parameter, 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;
}

A% is used to manage a sequence that contains a repeated value, which receives two parameters, the first is the value to be repeated and the second is the number of times it is repeated.

Then the Enumerable.Repeat of Select method is used, iterating each line and using the expression LINQ that receives as a parameter random.Next that represents the maximum return number.

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

string puts all returned characters into an array of characters.

.ToArray() transforms this array of characters into a string.

    
01.09.2015 / 21:38