Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a dynamic DataTable into a List<Dictionary<string,string>>

I want an elegant way to take a DataTable like this one :

enter image description here

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.

like image 974
Yaron Levi Avatar asked Nov 13 '13 16:11

Yaron Levi


People also ask

How do you convert a data table to a dictionary?

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.

How to convert DataTable to List of Dictionary in c#?

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.


1 Answers

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
    )
)
like image 87
SLaks Avatar answered Nov 15 '22 00:11

SLaks