0

I have a list based of a custom class in C# and I am attempting to use a foreach loop to select each item in the index and using Random, randomly generate an INT for each item.

However, every item in the foreach loop changes to the same value. Is there away to change this?

this is my custom list:

List<patient> p = new List<patient>();

this is how i add items to the list:

p.Add(new patient(pname, pdob, ploc));

and this is the foreach loop in running inside a system.timers event.

foreach(patient ps in p)
{
    ps.ploc = new Random().Next(80, 220);
}

an example output would be all items have a plocation(ploc) of 120 instead of each item having its own random.

Any solution would be greatly appreciated.

Codor
  • 17,447
  • 9
  • 29
  • 56
Robbie
  • 294
  • 1
  • 2
  • 14

3 Answers3

2

Try following, you are creating a new random with same seed for every patient, thus getting the same "random" numbers when calling Next()

var rnd = new Random();
foreach(patient ps in p)
{
    ps.ploc = rnd.Next(80, 220);
}
Janne Matikainen
  • 5,061
  • 15
  • 21
2

Initialise the Random outside the foreach

Random random = new Random();
foreach(patient ps in p)
{
    ps.ploc = random.Next(80, 220);
}
SimonPJ
  • 756
  • 9
  • 21
2

The problem is that you generade a new instance of Random in each iteration, using the same seed; consequently the same result is returned in each call. Change the loop the the following code.

var iRandom = new Random();
foreach(patient ps in p)
{
    ps.ploc = iRandom.Next(80, 220);
}
Codor
  • 17,447
  • 9
  • 29
  • 56