C#中的随机数生成器问题

Phi*_*lip 3 c# random numbers

很久以后,我设法让我的问题来自于我在第一个问题中询问的程序.它将一个随机数添加到列表中以用作ID号,然后将其导出到Excel.但是当我在我的数据文件中使用2个以上的数据成员时,我遇到了一个问题:我生成的随机数加倍,导致我的程序崩溃.

static Dictionary<string,Backup> getData()
{

    Dictionary<string, Backup> bDict = new Dictionary<string, Backup>();
    StreamReader reader = new StreamReader("/data/storedata.txt");

    while (!reader.EndOfStream)
    {

        string line = reader.ReadLine();
        string[] parts = line.Split(' ');

        string item = parts[0];
        string owner = parts[1];

        Random rnd = new Random();
        int test = rnd.Next(item.Length+10000);//For every 'item' a Random number is generated.(the +10000 is simply to produce a 4-digit number)

        //Console.WriteLine(test);//Testing 
        Backup BP = new Backup(item, owner,test);

        bDict.Add(test.ToString(), BP);//Adding to the Dictionary.

        //Console.WriteLine(string.Format("{0}, {1}, {2}", item, test, owner));

    }
    return bDict;
}//Read file, Grabed data and stored it in a List.
Run Code Online (Sandbox Code Playgroud)

我正在/试图做的是有一种检查,如果两个数字相同,则生成一个新数字作为替换(或者做同样事情的其他方式).我试过if语句,但VS一直在问我是否打算与其他东西进行比较.我在Stackoverflow上查看了这些内容,但答案与我的代码所发生的情况不符.任何帮助表示赞赏.

常见问题数据文件将有超过500'项目'没有最小/最大

干杯

Tim*_*ter 5

我生成的随机数加倍,导致我的程序崩溃.

你必须重复使用相同的随机实例,所以在循环之外创建它,否则它会同时播种,导致相同的数字.

MSDN:

随机数生成从种子值开始.如果重复使用相同的种子,则生成相同的数字序列.

除此之外,你必须检查数字是否已存在于Dictionary:

Random rnd = new Random();
while (!reader.EndOfStream)
// ...

while(bDict.ContainsKey(test.ToString()))
    test = rnd.Next(item.Length + 10000);
Run Code Online (Sandbox Code Playgroud)