Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
    }
}
like image 236
Brian Avatar asked Mar 19 '09 17:03

Brian


People also ask

At what temperature can you test an air conditioner?

HVAC manufacturers usually recommend that users do not operate their units for prolonged periods of time if the temperature is lower than 65 degrees Fahrenheit. If you need to test your unit, then you should wait until the temperature has been above 60 degrees Fahrenheit for at least three days first.


1 Answers

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;
    }    
}
like image 137
Chris Doggett Avatar answered Dec 03 '22 21:12

Chris Doggett