Non-repetitive random number

后端 未结 10 1946
囚心锁ツ
囚心锁ツ 2020-11-27 08:10

To generate Random numbers from 1- 20 I need to pick selective and it should not be repetitive.

How to do this in C#

Note I need to loop through as like this

10条回答
  •  孤街浪徒
    2020-11-27 09:06

    The following way is very good way, I use a string over here, you can change the type of the list to whatever you want..., try it:

                List NamesList = new List() { "Name1", "Name2", "Name3", "Name4", "Name5" };
                Random rnd = new Random();
                //Now to get random of the above "Without Repeating.."
                for (int i = 0; i <= NamesList.Count - 1; i++)
                {
                    int TheSelectedRand = rnd.Next(NamesList.Count);
                    string MyRandNumber = NamesList[TheSelectedRand];
    
                    //Print or use your item here
    
                    NamesList.Remove(NamesList[TheSelectedRand]);
                }
    

提交回复
热议问题