(In this windows form application) I’m trying to read data from a file into a hash table and populate text boxes with the data in the hash table but when I run the code I’m always thrown the exception “Item has already been added. Key in dictionary: ” Key being added: ” “
Initial code:
string[] fileLines = File.ReadAllLines(@"C:path/ajand.txt");
foreach (string line in fileLines)
{
// to split the first 9 chars in the string and use them as key values
string[] match = Regex.Split(line, line.Substring(0,9));
hT.Add(match[0], line);
}
so i tried checking for key duplicates with the following code
string[] fileLines = File.ReadAllLines(@"C:path/ajand.txt");
foreach (string line in fileLines)
{
string[] match = Regex.Split(line, line.Substring(0,9));
if(!hT.ContainsKey(match[0])) // to check duplicates
hT.Add(match[0], line);
}
But when I run the program the corresponding text boxes are not populated with the data that “seems” to have been added to the hash table.
Please any ideas what the problem is.
If I understand correctly you could use a function like this one:
Dictionaries are great for repeatedly looking up keys in a large set of keys. But if you only need to hold a bunch of key/value pairs in a collection so that you can later iterate through them, I would go with a List<> instead.
Here is a version of the above function which uses a StreamReader instead of loading the complete file in a string array.