Generating random, unique values C#

前端 未结 17 1177
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:26

I\'ve searched for a while and been struggling to find this, I\'m trying to generate several random, unique numbers is C#. I\'m using System.Random, and I\'m us

17条回答
  •  死守一世寂寞
    2020-11-22 15:08

    It's may be a little bit late, but here is more suitable code, for example when you need to use loops:

                List genered = new List();
    
                Random rnd = new Random();
    
                for(int x = 0; x < files.Length; x++)
                {
                    int value = rnd.Next(0, files.Length - 1);
                    while (genered.Contains(value))
                    {
                        value = rnd.Next(0, files.Length - 1);
                    }
                    genered.Add(value);
    
                    returnFiles[x] = files[value];
                }
    

提交回复
热议问题