Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dynamic list to datatable c#

Tags:

c#

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 
like image 839
ykel Avatar asked Feb 10 '14 09:02

ykel


3 Answers

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);
like image 65
Majedur Avatar answered Nov 12 '22 21:11

Majedur


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

like image 27
AHMAD SUMRAIZ Avatar answered Nov 12 '22 22:11

AHMAD SUMRAIZ


 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;
    }
like image 3
Nimesh.Nim Avatar answered Nov 12 '22 21:11

Nimesh.Nim