Getting random numbers from a list of integers

前端 未结 7 890
慢半拍i
慢半拍i 2021-02-08 10:59

If I have a list of integers:

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

How would I get 3 random integer

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 11:29

    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.

提交回复
热议问题