Daniel Revell
Daniel Revell

Reputation: 8586

How to get the key of a Hashtable entry

I've got a hashtable that I want to update from a second hashtable. For any of the keys that match I want to copy the value over. The problem I have is when I enumerate the hashtable keys and try to cast each to a string I receive an exception about casting a Guid to a String. Well it's the string I want. When you use the index operator with something like hashtable["FirstName"] then I expect FirstName to be the key. It might use Guids underneath I guess but I need to get out the string for the key, the key value.

private void UpdateSharePointFromInfoPath(Hashtable infopathFields)
{
    // Go through all the fields on the infopath form
    // Invalid Cast Exception Here
    foreach (String fieldName in infopathFields.Keys)
    {
        // If the same field is on sharepoint    
        if (workflowProperties.Item.Fields.ContainsField(fieldName))
        {
            // Update the sharepoint field with the new value from infopath
            workflowProperties.Item[fieldName] = infopathFields[fieldName];
        }
    }
    // Commit the changes
    workflowProperties.Item.Update();
}

EDIT I don't create either of these hashtables. The keys have strings somewhere because I can put the field name in like the following and get the value of the field out. I'm trying to make a shorthand way of doing the following for every field:

workflowProperties.Item["FirstName"] = infopathFields["FirstName"];
workflowProperties.Item["LastName"] = infopathFields["LastName"];
workflowProperties.Item["Address"] = infopathFields["Address"];
workflowProperties.Item["DOB"] = infopathFields["DOB"];
ect...

EDIT It's been said that the hashtable uses Guids, but it also obviously has a string inside else I wouldn't be able to do infopathFields["FirstName"]. It's the value on the string I pass in there that I want.

Upvotes: 4

Views: 33979

Answers (6)

HEMANT KUMAR
HEMANT KUMAR

Reputation: 1

To get largest integer key from Hash table:

public class Example
{
    public void hashTableMethod()
    {
        Hashtable ht = new Hashtable();
        ht.Add(5002894, "Hemant Kumar");
        ht.Add(5002895, "Himanshee Ratnakar");
        ht.Add(5002896, "Pooja Bhatnagar");
        ht.Add(5002897, "Hina Saxena");
        ht.Add(5002898, "Kanika Aneja");
        ht.Add(5002899, "Hitesh Chaudhary");

        Console.Write("\nNumber of Key-Value pair elements in HashTable are : {0}",ht.Count);
        Console.WriteLine("Elements in HashTable are: ");
        ICollection htkey = ht.Keys;
        foreach (int key in htkey)
        {
            Console.WriteLine("{0}. {1}",key,ht[key]);
        }
        string ch="n";
        do
        {
            Console.Write("\n\nEnter the name to check if it is exist or not, if not then it will add: ");
            string newName=Console.ReadLine();
            if(ht.ContainsValue(newName))
            {
                Console.Write("\nYour Name already Exist in the list!!");
            }
            else
            {
                Console.Write("\nSorry that name doesn't exist but it will be added!!");
                int getKey = 0;

                int[] htk= new int[ht.Count];
                ht.Keys.CopyTo(htk,0);

                string[] val=new string[ht.Count];
                ht.Values.CopyTo(val,0);

                Array.Sort(htk,val);
                foreach (int id in htk)
                {
                    getKey = id;  
                }
                ht.Add(getKey+1,newName);
            }
            Console.Write("\nDo you want to search more??(y/n) :");
            ch=Console.ReadLine();
        }while(ch=="y"||ch=="Y");

        Console.Write("\nNew List Items: \n");
        ICollection htkeys = ht.Keys;
        foreach (int key in htkeys)
        {
            Console.WriteLine("{0}. {1}",key,ht[key]);
        }
    }
}

Upvotes: 0

harryovers
harryovers

Reputation: 3138

Every item is a Key/Value pair of format DictionaryEntry

foreach (DictionaryEntry de in infopathFields)
        {        
            string fieldName = de.Key as string;         
                if (workflowProperties.Item.Fields.ContainsField(fieldName))        
                {           
                    workflowProperties.Item[fieldName] = infopathFields[fieldName];        
                }    
        }    

        workflowProperties.Item.Update();

Upvotes: 9

Jonathan Beerhalter
Jonathan Beerhalter

Reputation: 7407

The standard version of the Hashtable can have different type keys, so most of your keys may be strings, but some of your keys may be GUIDs. I'm willing to bet that is the case and is causing your issue. The following little console app demonstrates the problem.

    static void Main(string[] args)
    {
        System.Collections.Hashtable htable = new System.Collections.Hashtable();
        htable.Add("MyName", "WindyCityEagle");
        htable.Add("MyAddress", "Here");
        htable.Add(new Guid(), "That Was My Guid");

        int loopCount = 0;
        foreach (string s in htable.Keys)
        {
            Console.WriteLine(loopCount++.ToString());
            Console.WriteLine(htable[s]);
        }
    }

You'll get the exact same exception that you're reporting here.

My suggestion to fix the problem would be to go with the following

private void UpdateSharePointFromInfoPath(Hashtable infopathFields)
{
    // Go through all the fields on the infopath form
    // Invalid Cast Exception Here
    foreach (object key in infopathFields.Keys)
    {

        string wfpKey = key.ToString();
        // If the same field is on sharepoint    
        if (workflowProperties.Item.Fields.ContainsField(wfpKey))
        {
            // Update the sharepoint field with the new value from infopath
            workflowProperties.Item[wfpKey] = infopathFields[key];
        }
    }
    // Commit the changes
    workflowProperties.Item.Update();
}

Upvotes: 1

thecoop
thecoop

Reputation: 46098

The objects stored in the hashtable are Guid objects, so to get a string you need to call ToString() on the object you get from the key enumerator. I would also recommend using the generic Dictionary<K,V> class instead of Hashtable, as that would catch problems like this at compile time rather than runtime.

Upvotes: 0

James Bloomer
James Bloomer

Reputation: 5322

If the type of the values of infopathFields is a Guid then the types of the values of workflowProperties will have to be Guids. I can't see from the snippet what workflowProperties is defined as.

To convert a Guid to a string use Guid.ToString()

Upvotes: 0

Pharabus
Pharabus

Reputation: 6062

What creates the Hashtable? the key is actually an object so it sounds like whatever populated it has no implicit cast to a string

Upvotes: 0

Related Questions