将哈希表转换为数据表的更好方法

lea*_*ner 0 c#

有没有更好的方法将哈希表转换为数据表

private DataTable ConvertHastTableToDataTable(System.Collections.Hashtable hashtable)
{

   var dataTable = new DataTable(hashtable.GetType().Name);
    dataTable.Columns.Add("Key",typeof(object));
    dataTable.Columns.Add("Value", typeof(object));
    IDictionaryEnumerator enumerator = hashtable.GetEnumerator();
    while (enumerator.MoveNext())
    {
     dataTable.Rows.Add(enumerator.Key, enumerator.Value);

    }
    return dataTable;
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 5

这是一种非常简单的方法.然而,在这种特殊情况下,真正的惯用方法是foreach直接使用构造.

foreach (DictionaryEntry item in hashtable)
{
    // work with item.Key and item.Value here
}
Run Code Online (Sandbox Code Playgroud)

对于将来的编程,您可能希望继续使用Dictionary<TKey, TValue>集合,这允许比传统的非泛型更强的类型Hashtable.例:

Dictionary<string, double> dictionary = new Dictionary<string, double>();
dictionary.Add("Foo", 1.2);
dictionary.Add("Bar", 2.4);

foreach (KeyValuePair<string, double> pair in dictionary)
{
    // work with pair.Key and pair.Value, each strongly typed
}
Run Code Online (Sandbox Code Playgroud)