6
I have a List<int> numeros
It is possible to return a random element from this list?
6
I have a List<int> numeros
It is possible to return a random element from this list?
10
You can do as follows in .net
:
var lista = new List<int>{3,5,1,8,4,9};
var rnd = new Random();
var valorAleatorio = lista[rnd.Next(lista.Count)];
4
For a have that in .NET
do:
IList<int> listaNumeros = new List<int>() { 95, 4, 9, 52, 40, 800, 90, 11, 2, 9, 4, 92, 8, 91, 120, 111 };
Random rand = new Random(DateTime.Now.Millisecond);
int resultado = listaNumeros[rand.Next(listaNumeros.Count)]
Example: Demo
References:
2
An addition to the other answers, in the form of a extension method
:
private static Random _randGen = new Random();
public static T GetRandomElement<T>(this IList<T> source)
{
return source[_randGen.Next(0, source.Count)];
}
1
Yes. See the following example:
List<Integer> numeros = new ArrayList<Integer>();
numeros.add(1);
numeros.add(2);
numeros.add(3);
numeros.add(4);
numeros.add(5);
numeros.add(6);
numeros.add(7);
Random gerador = new Random();
int index = gerador.nextInt(numeros.size());
System.out.println(numeros.get(index));
C#. I put it in the tag, but forgot to put it in the scope of the question. Thank you!
Puts! Just now I noticed the tags c# and .net. But even if it is in java it can use the same logic.
Browser other questions tagged c# .net list random
You are not signed in. Login or sign up in order to post.
It is preferable to call the builder of
Random
no arguments. The argument-free constructor usesEnvironment.TickCount
(2 31 possible values) like Seed, which has a much larger entropy thanDateTime.Now.Millisecond
(1000 possible values).– dcastro
It is better to use default behavior. Besides, the quantity of number is irrelevant - there is no performance degradation. Quite the contrary, there is a (slight) degradation of performance in using
DateTime.Now.Millisecond
because it implies parsing the date of the system, interpreting the time zone, and interpreting the milliseconds of the current time.Environment.TickCount
and' a direct call to the kernel and e' therefore more efficient and ensures a more random result.– dcastro