Select N random elements from a List in C#


I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string>.

7/21/2016 12:27:11 PM

Accepted Answer

Iterate through and for each element make the probability of selection = (number needed)/(number left)

So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that.

9/7/2008 3:16:16 AM

Using linq:

YourList.OrderBy(x => rnd.Next()).Take(5)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow