I have List<int> numeros
Is it possible to return a random element from this list?
I have List<int> numeros
Is it possible to return a random element from this list?
To have this 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:
You can do this as .net
:
var lista = new List<int>{3,5,1,8,4,9};
var rnd = new Random();
var valorAleatorio = lista[rnd.Next(lista.Count)];
One addition to the other responses, in the form of extension method
:
private static Random _randGen = new Random();
public static T GetRandomElement<T>(this IList<T> source)
{
return source[_randGen.Next(0, source.Count)];
}
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));