DataTable to IEnumerable of Dictionaries in C#

2015-01-31 in .net, c#

A snippet to convert a DataTable to an IEnumerable of Dictionaries, implemented in C#. Useful in cases where the structure returned by a query is unknown due to dynamic query generation and sacrificing strong typing is acceptable.

public IEnumerable<Dictionary<string, object>> ToDictionaries(DataTable table)
{
    var columns = table.Columns.Cast<DataColumn>();
    return table.AsEnumerable()
        .Select(r => columns.ToDictionary(c => c.ColumnName,
                                          c => r.Field<object>(c.ColumnName)));
}

When retrieving these values you'll need to make sure to use the proper datatype for casting.

var table = GetData("SELECT 1 + 1 AS Two, 'HELLO' AS Greeting");
var data = ToDictionaries(table);
var number = (int)data["Two"];
var greeting = (string)data["Greeting"];