Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random numbers from a list of integers

Tags:

c#

random

int

If I have a list of integers:

List<int> myValues = new List<int>(new int[] { 1, 2, 3, 4, 5, 6 } );

How would I get 3 random integers from that list?

like image 939
George Harnwell Avatar asked Jul 08 '13 15:07

George Harnwell


2 Answers

Combining the other answer with this answer can lead you to the following:

var rand = new Random();
var numbers = Enumerable.Range(1, 6).OrderBy(i => rand.Next()).ToList();

In this case 1 is the starting value (inclusive) and 6 is the number of integers to generate.

like image 171
Jim Buck Avatar answered Oct 18 '22 02:10

Jim Buck


or this:

myList.OrderBy(x => Guid.newGuid()).Take(3)
like image 32
Peter Kellner Avatar answered Oct 18 '22 01:10

Peter Kellner