1

I have a list

List<> list = new List<>();

I want to convert this to a data table.How it is possible?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    possible duplicate of [Convert generic List/Enumerable to DataTable?](http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable) – Sriram Sakthivel Feb 10 '14 at 07:34

1 Answers1

0

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