I want to know how to transform a DataTable into a Dictionary. I did something like this.
using System.Linq;
internal Dictionary GetDict(Da
i prefer this method:
public static List> GetDataTableDictionaryList(DataTable dt)
{
return dt.AsEnumerable().Select(
row => dt.Columns.Cast().ToDictionary(
column => column.ColumnName,
column => row[column].ToString()
)).ToList();
}
the reason why is because this code can also deal with Booleans or other data types by calling the ToString method.
Notice this returns a list of dictionaries, you can modify it to a dictionary of dictionaries if you have key for each row.
iterate over a bool column might look like so:
var list = GetDataTableDictionaryList(dt);
foreach (var row in list)
{
if (row["Selected"].Equals("true", StringComparison.OrdinalIgnoreCase))
{
// do something
}
}