C# – How to test if a C# Hashtable contains a specific key/value pair

c++hashtable

I'm storing a bunch of supposedly-unique item IDs as a key and the file locations as the value in a hash table while traversing a table. While I am running through it, I need to make sure that they key/location pair is unique or throw an error message. I have the hashtable set up and am loading the values, but am not sure what to test:

Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
    if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
        //what goes here?  Would be contains item["Path"] as the value for the key)
    {
        //throw error
    }
}

Best Solution

Try this:

Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
    if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
        check_for_duplicates[item["ItemID"]].Equals(item["Path"]))
    {
        //throw error
    }
}

Also, if you're using .NET 2.0 or higher, consider using Generics, like this:

List<Item> items; // Filled somewhere else

// Filters out duplicates, but won't throw an error like you want.
HashSet<Item> dupeCheck = new HashSet<Item>(items); 

items = dupeCheck.ToList();

Actually, I just checked, and it looks like HashSet is .NET 3.5 only. A Dictionary would be more appropriate for 2.0:

Dictionary<int, string> dupeCheck = new Dictionary<int, string>();

foreach(Item item in items) {
    if(dupeCheck.ContainsKey(item.ItemID) && 
       dupeCheck[item.ItemID].Equals(item.Path)) {
        // throw error
    }
    else {
        dupeCheck[item.ItemID] = item.Path;
    }    
}
Related Question