I want to add a random number to a list to be used as a ID number and then exports it to Excel. However i cam across a probelm when using more than 2 data members in my datafile: The Random numbers i generate double up, causing my program to crash.
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.
Andrew Deniel
14-Oct-2013The Random numbers i generate double up, causing my program to crash.
You just have to check if the number already exists in the Dictionary:
while(bDict.ContainsKey(test.ToString()))
test = rnd.Next(item.Length + 10000);