Is there any better way of converting a hashtable to datatable
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;
}
That’s a pretty straightforward method of doing it. However, the real idiomatic way in this particular case is to just use the
foreachconstruct directly.For future programming, you probably want to go ahead and use a
Dictionary<TKey, TValue>collection, which allows for stronger typing than the legacy, non-genericHashtable. Example: