8
I need a C# function that manages a String
of random alphabetic and numerical characters of size N
.
8
I need a C# function that manages a String
of random alphabetic and numerical characters of size N
.
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.Next
which 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.
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 c# .net string random
You are not signed in. Login or sign up in order to post.
You got a excellent response in Codereview: Random String Generation - Base36 and Optimization
– dcastro