Convert DataTable to Dictionary

/// <summary>
/// Converts a DataTable to a dictionary. (NON PERFORMANT)
/// </summary>
/// <remarks>
/// This method is usually used when running dynamic sql in databases that don't support
/// stored procs. The columns returned are unknown so we create a dictionary which AutoMapper
/// will use to match properties on the DTOs
/// </remarks>
/// <param name="dt">The dt.</param>
/// <returns></returns>
public static List<Dictionary<string, object>> DataTableToDictionary(this DataTable dt)
    List<Dictionary<string, object>> dictionaries = new List<Dictionary<string, object>>();
    foreach (DataRow row in dt.Rows)
        Dictionary<string, object> dictionary = Enumerable.Range(0, dt.Columns.Count)
            .ToDictionary(i => dt.Columns[i].ColumnName, i => row.ItemArray[i]);

    return dictionaries;

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.