ToDataTable Method missed !!! #157

mirshahreza opened this Issue Sep 26, 2012 · 3 comments

3 participants


I used the library , it is good and friendly , but there is no method for get a resultset in DataTable.
How can I fetch TOP 1 record in DataRow format?


Ad below extension methods to your file

    /// <summary>
    /// Extension method to convert dynamic data to a DataTable. Useful for databinding.
    /// </summary>
    /// <param name="items"></param>
    /// <returns>A DataTable with the copied dynamic data.</returns>
    public static DataTable ToDataTable(this IEnumerable<dynamic> items, string tableName = "Table1")
        var data = items.ToArray();
        if (data.Count() == 0) return null;

        var dt = new DataTable(tableName);
        foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
        foreach (var d in data)
            dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
        return dt;

    public static IEnumerable<dynamic> AsDynamicEnumerable(this DataTable table)
        // Validate argument here..

        return table.AsEnumerable().Select(row => new DynamicRow(row));

    private sealed class DynamicRow : DynamicObject
        private readonly DataRow _row;

        internal DynamicRow(DataRow row) { _row = row; }

        // Interprets a member-access as an indexer-access on the
        // contained DataRow.
        public override bool TryGetMember(GetMemberBinder binder, out object result)
            var retVal = _row.Table.Columns.Contains(binder.Name);
            result = retVal ? _row[binder.Name] : null;
            return retVal;

ToDataTable Method is ok for fields with text datatype but for Image fields it is not a good Idea.
There must be a perfect method for make datatable with exact data types....


You're welcome to do what you need in your projects - this isn't something that needs to be in trunk.

@robconery robconery closed this Dec 3, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment