-2

I want to get random number in per repeat of foreach loop

 @foreach (var item in Model)
        {
            Random r = new Random();
            int s = r.Next(0, 5);                                             
            <span>@(s)</span>                   
        }

But I get same value instead of random value.

mohammad
  • 1,018
  • 2
  • 14
  • 27
  • 4
    Move this `Random r = new Random();` outside of the `foreach` loop. – Nasreddine Feb 01 '17 at 08:24
  • The instances of the `Random` class are creating too close in time. So they will all be seeded with the same random sequence. – Salah Akbari Feb 01 '17 at 08:26
  • Moreover, @S.Akbari - The Random instances are regularly generated with the same seed - due to being created too close in time – Ben Feb 01 '17 at 08:28
  • insert a little delay before `Random r = new Random()`, about 20milliseconds, then values will be different – Sergio Feb 01 '17 at 08:53

1 Answers1

2
Random r = new Random();

@foreach (var item in Model)
        {
            int s = r.Next(0, 5);                                             
            <span>@(s)</span>                   
        }
bxc00zzy
  • 104
  • 2
  • 14