C# 如何获取Hashtable条目的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1848299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:22:23  来源:igfitidea点击:

How to get the key of a Hashtable entry

c#hashtable

提问by Dan Revell

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.

我有一个哈希表,我想从第二个哈希表更新。对于匹配的任何键,我想复制该值。我遇到的问题是,当我枚举哈希表键并尝试将每个键转换为字符串时,我收到一个关于将 Guid 转换为字符串的异常。嗯,这是我想要的字符串。当您将索引运算符与 hashtable["FirstName"] 之类的东西一起使用时,我希望 FirstName 是关键。我猜它可能会在下面使用 Guids,但我需要取出键的字符串,键值。

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();
}

EDITI 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...

EDITIt'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.

编辑据说哈希表使用了 Guids,但它显然也有一个字符串,否则我将无法执行 infopathFields["FirstName"]。这是我在那里传递的字符串中我想要的值。

采纳答案by harryovers

Every item is a Key/Value pair of format DictionaryEntry

每个项目都是一个键/值对格式 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();

回答by Pharabus

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

什么创建了哈希表?键实际上是一个对象,所以听起来就像填充它没有隐式转换为字符串

回答by James Bloomer

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.

如果 infopathFields 的值类型是 Guid,则工作流属性值的类型必须是 Guid。我无法从片段中看到工作流属性的定义。

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

要将 Guid 转换为字符串,请使用Guid.ToString()

回答by thecoop

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.

存储在哈希表中的对象是 Guid 对象,因此要获取字符串,您需要调用ToString()从键枚举器获取的对象。我还建议使用泛型Dictionary<K,V>类而不是 Hashtable,因为这会在编译时而不是运行时捕获此类问题。

回答by Jonathan Beerhalter

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.

Hashtable 的标准版本可以有不同类型的键,因此大多数键可能是字符串,但有些键可能是 GUID。我敢打赌就是这种情况并且导致了您的问题。下面的小控制台应用程序演示了这个问题。

    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();
}

回答by HEMANT KUMAR

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]);
        }
    }
}