Transform a DataTable into Dictionary C#
The generic method ToDictionary
has 3 parameters. You left one off, so it doesn't know what to do. If you want to specify all of the parameters, it would be <DataRow, string, object>
.
internal Dictionary<string,object> GetDict(DataTable dt)
{
return dt.AsEnumerable()
.ToDictionary<DataRow, string, object>(row => row.Field<string>(0),
row => row.Field<object>(1));
}
Of course, if you leave them off, the compiler is able to infer the types, so you don't get the error.
All the previos answers didn't help me, so I did this:
myList = dt.AsEnumerable()
.ToDictionary<DataRow, string, string>(row => row[0].ToString(),
row => row[1].ToString());
and it worked great!
i prefer this method:
public static List<Dictionary<string, string>> GetDataTableDictionaryList(DataTable dt)
{
return dt.AsEnumerable().Select(
row => dt.Columns.Cast<DataColumn>().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
}
}