11

am searching and cracking my brain on how to convert a dynamic list to a databale, c#, please advise, thanks

List<dynamic>dlist=new List<dynamic>

to

DataTable 
zey
  • 5,939
  • 14
  • 56
  • 110
Neo
  • 717
  • 2
  • 11
  • 26
  • You mean, each property/field from the items should become column in datatable? What if every item in `dlist` is of different type? And the most important: What have you tried already? Show your effort. – MarcinJuraszek Feb 10 '14 at 09:06

9 Answers9

12

I think you looking something like this. Hope it's working for you.

From dynamic list to DataTable:

   List<dynamic> dlist=new List<dynamic> 
   var json = JsonConvert.SerializeObject(dlist);
   DataTable dataTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Also to get JsonString from DataTable:

string JSONresult = JsonConvert.SerializeObject(dataTable);
Majedur
  • 3,074
  • 1
  • 30
  • 43
5

The following is the method through which you can convert any list object to datatable..

 public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }

http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list-to-datatable?forum=csharpgeneral

AHMAD SUMRAIZ
  • 535
  • 8
  • 21
3
 public DataTable ToDataTable<T>(dynamic items)
    {

        DataTable dtDataTable = new DataTable();
        if (items.Count == 0) return dtDataTable;

        ((IEnumerable)items[0]).Cast<dynamic>().Select(p => p.Name).ToList().ForEach(col => { dtDataTable.Columns.Add(col); });

        ((IEnumerable)items).Cast<dynamic>().ToList().
            ForEach(data =>
            {
                DataRow dr = dtDataTable.NewRow();
                ((IEnumerable)data).Cast<dynamic>().ToList().ForEach(Col => { dr[Col.Name] = Col.Value; });
                dtDataTable.Rows.Add(dr);
            });
        return dtDataTable;
    }
Nimesh.Nim
  • 388
  • 2
  • 9
  • 1
    This worked for me, though I had to swap "Key" in for "Name" since my enumerable contained KeyValuePairs – Joe Zack Mar 01 '18 at 14:58
  • I don't think this is going to work if the IEnumerable contains no items - it will return a DataTable with no columns or rows. I'd want a DataTable with columns but no rows – Colin May 22 '20 at 08:08
2

I don't know why you need this, however, you can use this ObjectShredder using reflection which can convert anything to DataTable, so even dynamic or anonymous types:

Implement CopyToDataTable<T> Where the generic Type T Is Not a DataRow

However, my suggestion is to not name that extension method CopyToDataTable but for example CopyAnyToDataTable to avoid conflicts with the existing extension method CopyToDataTable.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Use this function ,

public static DataTable ConvertToDatatable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
    }
zey
  • 5,939
  • 14
  • 56
  • 110
0

If the underlying type is ExpandoObject, then you need to check for IDictionary instead of going via reflection. Hopefully this helps someone else in the future:

    public static DataTable ConvertToDataTable<T>(IEnumerable<T> data)
    {
        DataTable table = new DataTable();
        foreach (T item in data)
        {
            if (item is IDictionary<string, object> dict)
            {
                foreach (var key in dict)
                {
                    table.Columns.Add(key.Key, key.Value?.GetType() ?? typeof(object));
                }
                break;
            }
            foreach (var prop in typeof(T).GetProperties())
            {
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            break;
        }

        DataRow row = null;
        foreach (T item in data)
        {
            if (item is IDictionary<string, object> dict)
            {
                row = table.NewRow();
                foreach (var key in dict)
                {
                    row[key.Key] = key.Value;
                }
                table.Rows.Add(row);
                continue;
            }

            row = table.NewRow();
            foreach (var prop in typeof(T).GetProperties())
            {
                row[prop.Name] = prop.GetValue(item);
            }
            table.Rows.Add(row);
        }
        return table;
    }
Daniel Lorenz
  • 4,178
  • 1
  • 32
  • 39
  • I don't think this is going to work if the IEnumerable contains no items - it will return a DataTable with no columns or rows. I'd want a DataTable with columns but no rows – Colin May 22 '20 at 08:06
  • @Colin If you are using Dynamic/ExpandoObject underneath, you wouldn't have any columns to specify unless you had at least one item in that list because otherwise type T is really nothing since it wouldn't even be defined. – Daniel Lorenz May 22 '20 at 13:32
0

To Convert the Dynamic List object into DataTable using C#

 public DataTable DynamicToDT(List<object> objects)
        {
            DataTable dt = new DataTable("StudyRecords"); // Runtime Datatable          
            string[] arr = { "Name", "Department", "CollegeName", "Address" };// Column Name for DataTable
            if (objects != null && objects.Count > 0)
            {
                for (int i = 0; i < objects.Count; i++)
                {
                    dt.Columns.Add(arr[i]);
                    if (i == 0)
                    {
                        var items = objects[0] as IEnumerable<string>;
                        foreach (var itm in items)
                        {
                            DataRow dr1 = dt.NewRow(); // Adding values to Datatable  
                            dr1[arr[i]] = itm;
                            dt.Rows.Add(dr1);
                        }
                    }
                    else
                    {
                        var items = objects[i] as IEnumerable<string>;
                        int count = 0;
                        foreach (var itm in items)
                        {
                            dt.Rows[count][arr[i]] = itm;
                            count++;
                        }
                    }
                }

                return dt; // Converted Dynamic list to Datatable  
            }
            return null;
        }
0

public static DataTable DynamicToDT(List objects)

    {
        var data = objects.ToArray();
        if (data.Count() == 0) return null;
        var dt = new DataTable();
        foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
        {
            dt.Columns.Add(key);
        }
        foreach (var d in data)
        {
            dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
        }
        return dt;
    }
0
// Obtem a lista dinamica via chamada API
List<dynamic> resultado = ExecutaQuery(sql);

// converte a lista dinamica com o resultado em JSON
string json = JsonConvert.SerializeObject(resultado);

// converte o json em datatable
DataTable dataTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
  • Please be sure to explain your code in English, as you're currently on the English language version of Stack Overflow. – Jeremy Caney Jul 16 '22 at 19:32