samedi 31 octobre 2015

Add random integer to hash set only if in another list

I have the following code:

Random rand = new Random();
HashSet<int> hsP = new HashSet<int>();
int tempRandVal = rand.Next(0,10000); //random number between 0 and 1000
var rng = Enumerable.Range(0,10000).Where(i => listP.Contains(i));  //create range with previously populated list

        while (hsP.Count < 200)
        {

            if(rng.Contains(tempRandVal))
            {
                hsP.Add(tempRandVal);
            } 
            else
            {
                tempRndValue = rnd.Next(10000);
            }
        }

The above is causing an infinite loop. An extra eye would be great.




Aucun commentaire:

Enregistrer un commentaire