Get random element from a ListT

6

I have List<int> numeros

Is it possible to return a random element from this list?

    
asked by anonymous 09.07.2014 / 16:12

4 answers

4

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:

09.07.2014 / 16:25
10

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)];
    
09.07.2014 / 16:25
2

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)];
}
    
09.07.2014 / 18:10
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)); 
    
09.07.2014 / 16:22