Random () generating repeated numbers

7

I'm developing a small application to import XML, which searches for the items in the note and performs the search of the same in% of the internal% of the company. When the item is not found, the link is done manually and this information is saved in a DB table to, next time, the program finds the item.

My problem is in the ItemFornecXItemEmpresa generation, which is generated based on the day and time of insertion and 5 more random numbers:

for (int i = 0; i < itens.Count; i++)
{
    if (itens[i].Novo == true)
    {
        Random rand = new Random();
        string ano = String.Format("{0:yy}", DateTime.Now);
        string mes = String.Format("{0:MM}", DateTime.Now);
        string dia = String.Format("{0:dd}", DateTime.Now);
        string hora = String.Format("{0:hh}", DateTime.Now);
        string mili = String.Format("{0:ff}", DateTime.Now);
        string random = rand.Next(10000,99999).ToString();

    string id = ano + mes + dia + hora + mili + random;
    [...]
    }
}

And every insertion I make I have this type of ObjID generated:

150325094512431
1503250946*44723*
1503250947*44723*
150325094929997
150325095062289
1503250951*94581*
1503250952*94581*
201513031638315
201516031131187
201516031136284
201516031137201

I observe several%% of% s repeated. Is there any logic to this?

    
asked by anonymous 25.03.2015 / 13:35

1 answer

8

Yes, there is. Your code is initializing the random seed every time inside the loop. Then you will repeat it. If you want different values you should start the seed only once, that is, you must remove the initialization of the loop variable. So:

Random rand = new Random();
for (int i = 0; i < itens.Count; i++) {
    if (itens[i].Novo == true) {
        string ano = String.Format("{0:yy}", DateTime.Now);
        string mes = String.Format("{0:MM}", DateTime.Now);
        string dia = String.Format("{0:dd}", DateTime.Now);
        string hora = String.Format("{0:hh}", DateTime.Now);
        string mili = String.Format("{0:ff}", DateTime.Now);
        string random = rand.Next(10000,99999).ToString();

    string id = ano + mes + dia + hora + mili + random;
    [...]
    }
}

To better understand and see usage examples, please read all of the documentation at Random() .

See an example demonstrating the problem:

using System;
using static System.Console;

public class Program {
    public static void Main() {
        var rand = new Random();
        for (int i = 0; i < 10; i++) {
            WriteLine(rand.Next(10000,99999));
        }
        WriteLine();
        for (int i = 0; i < 10; i++) {
            rand = new Random();
            WriteLine(rand.Next(10000,99999));
        }
    }
}

See running on dotNetFiddle .

    
25.03.2015 / 13:39