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

本文关键字:更好 方法 数据表 哈希表 转换 | 更新日期: 2023-09-27 17:49:40

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

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

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

这是一种非常直接的方法。然而,在这个特殊的情况下,真正习惯的方法是直接使用foreach结构。

foreach (DictionaryEntry item in hashtable)
{
    // work with item.Key and item.Value here
}

对于将来的编程,您可能希望继续使用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
}

如果在数据类型中添加扩展。

//imports
using MMExtensions;
//your namespace
namespace MMExtensions {
    public static class DictionaryExtensions {
        public static DataTable ToDataTable<TKey, TValue>(
            this Dictionary<TKey, TValue> hashtable
        ){
            var dataTable = new DataTable(hashtable.GetType().Name);
            dataTable.Columns.Add("Key", typeof(object));
            dataTable.Columns.Add("Value", typeof(object));
            foreach (KeyValuePair<TKey, TValue> var in hashtable){
                dataTable.Rows.Add(var.Key, var.Value);
            }
            return dataTable;
        }
    }
    public static class HashtableExtensions {
        public static DataTable ToDataTable(this Hashtable hashtable) {
            var dataTable = new DataTable(hashtable.GetType().Name);
            dataTable.Columns.Add("Key", typeof(object));
            dataTable.Columns.Add("Value", typeof(object));
            foreach (DictionaryEntry var in hashtable){
                dataTable.Rows.Add(var.Key, var.Value);
            }
            return dataTable;
        }
    }
}

然后,您可以使用下列命令创建您的表。

DataTable dt = new Dictionary<string, int> {{"v1", 1}, {"v2", 2}}.ToDataTable();
DataTable dt2 = new Hashtable(){{"v1", 1}, {"v2", 2}}.ToDataTable();

注意,我并没有改变那么多。c#已经有了hashmap数据结构,它被称为字典。此外,当循环遍历集合时,使用foreach循环要好得多,因为它使用了更安全的循环方式。您也可以使用特殊类型var,但我认为它违背了这里的目的,因为您需要类型信息。

编辑:包含Hashtable扩展