Link to home
Start Free TrialLog in
Avatar of simonm_jp
simonm_jp

asked on

C# Iterate over Hashtable

Hi Experts,

When I use the following code to iterate over a Hashtable I get this error:   "Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'MyApplication.BLL.CategorySubType'."

        Hashtable categories = objComplaintSingleton.getCategorySubTypes();
        ComplaintCategory objComplaintCategory;
        foreach (CategorySubType objCategorySubType in categories)
        {
            objComplaintCategory = new ComplaintCategory();
            objComplaintCategory.ComplaintID = complaintId;
            objComplaintCategory.CategorySubTypeID = objCategorySubType.Id;
            objComplaintCategory.CategoryTypeID = objCategorySubType.CategoryTypeId;
            objComplaintCategory.Save();
            objComplaintCategory = null;
        }

Note the Hashtable holds string as a key and an object of type CategorySubType as the value.

Thanks.
Avatar of Jesse Houwing
Jesse Houwing
Flag of Netherlands image

use
 foreach (CategorySubType objCategorySubType in categories.Values)

to iterate over each value stored.

 There's also a property Keys which allows you to iterate over the keys.
The value references within a Hashtable are actually of type System.Collections.DictionaryEntry, so you may need to iterate over the values using this type, and then cast each one as needed.  E.g., try something like

    Hashtable categories = objComplaintSingleton.getCategorySubTypes();
    ComplaintCategory objComplaintCategory;
    foreach (System.Collections.DictionaryEntry dictEntry in categories)
    {
        CategorySubType objCategorySubType = (CategorySubType)dictEntry;
        objComplaintCategory = new ComplaintCategory();
        objComplaintCategory.ComplaintID = complaintId;
        objComplaintCategory.CategorySubTypeID = objCategorySubType.Id;
        objComplaintCategory.CategoryTypeID = objCategorySubType.CategoryTypeId;
        objComplaintCategory.Save();
        objComplaintCategory = null;
    }

More specifics about the System.Collections.Hashtable class at http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemcollectionshashtableclasstopic.asp
ASKER CERTIFIED SOLUTION
Avatar of Jesse Houwing
Jesse Houwing
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of simonm_jp
simonm_jp

ASKER

Doh! ... should have picked that one up myself.  

Thanks ToAoM.