Pick random element from a List<T>

Asked

Viewed 3,435 times

6

I have a List<int> numeros

It is possible to return a random element from this list?

4 answers

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


  • 2

    It is preferable to call the builder of Random no arguments. The argument-free constructor uses Environment.TickCount (2 31 possible values) like Seed, which has a much larger entropy than DateTime.Now.Millisecond (1000 possible values).

  • 2

    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.

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

You are not signed in. Login or sign up in order to post.