I want an elegant way to take a DataTable like this one :
And turn it into a :
List<Dictionary<string,string>> values = dataTable.ToDictionary();
Each dictionary in the list corresponds to a row. A dictionary contains the values of a row where the key is the column name and the value is the column value.
The method should support dynamic number of columns and names.
When we need to transform 2 columns of data table to a dictionary, we can use LINQ. Dictionary is a Key Value Pair collection and Key should be unique. You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store.
List<Dictionary<string,string>> values = dataTable. ToDictionary(); Each dictionary in the list corresponds to a row. A dictionary contains the values of a row where the key is the column name and the value is the column value.
You need to turn each row into a dictionary:
// Iterate through the rows...
table.AsEnumerable().Select(
// ...then iterate through the columns...
row => table.Columns.Cast<DataColumn>().ToDictionary(
// ...and find the key value pairs for the dictionary
column => column.ColumnName, // Key
column => row[column] as string // Value
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With