Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get a single random element from a List<>?

Tags:

.net

linq

I need to get a random element from a list (that is not two of the values in the list). The following works fine:

Company dest = companies
    .Where(cpy => cpy != src && cpy != plyr.PowerUpInAction.Passenger.Destination)
    .OrderBy(pu => rand.Next())
    .ToList()[0];

Is there a better (ie more efficient) way to do this? Converting to a list strikes me as extra work.

thanks - dave

like image 211
David Thielen Avatar asked Jan 08 '14 16:01

David Thielen


People also ask

How do you randomly get an element from a list?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

How do I pick a random item from a list in Python?

Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you generate a random number from a list of numbers?

Note: If you want to generate random number based on a list, you can use this formula =INDEX($I$2:$I$7, RANDBETWEEN(1, 6)), and press Enter key.

How do you select a random value from a list in Java?

First, we select a random index for using Random. nextInt(int bound) method. Instead of Random class, you can always use the static method Math. random()(random() method generate a number between 0 and 1) and multiply it with list size.


1 Answers

You could do .First() instead of .ToList()[0]

like image 75
TrueEddie Avatar answered Sep 19 '22 17:09

TrueEddie