42

I have a data list with some property. I want to convert that list data into data table. How to convert a list into datable.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2660267
  • 951
  • 4
  • 10
  • 9

3 Answers3

143

Add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);
    
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}
Jelle
  • 758
  • 2
  • 14
  • 36
Harshil Raval
  • 2,115
  • 1
  • 13
  • 10
  • 2
    how to call this function.thanks for reply – user2660267 Aug 07 '13 at 10:34
  • 3
    Suppose you have list of User.List rm = new List(); And in User class there FirstName,LastName,Address etc. properties. Then to convert this list to datatable , just use this DataTable UserDt = rm.ToDataTable(); – Harshil Raval Aug 07 '13 at 10:38
  • 1
    Do we need to add any namespace for this method to work? PropertyInfo[] not getting recognized. – Badhon Jain Apr 30 '14 at 05:48
  • 3
    ok, I got it, system.reflection; – Badhon Jain Apr 30 '14 at 05:52
  • 1
    click on the classname that has a red line underneath it (as in syntax error) and press ALT+SHIFT+F10. It will show you the namespaces. Select the top one which is System.Reflection. – Shezi May 28 '14 at 06:41
  • IF we pass this list List test = new List() its not working – Keerthi Kumar Apr 17 '15 at 12:57
  • 1
    above answer is giving me `Additional information: Parameter count mismatch.` – Jogi May 24 '16 at 18:42
  • Exactly what i need...Thanks a lot. – Kumar Jan 09 '18 at 11:35
  • FYI, when using this method for SqlBulkCopy, you will need to specify the column mappings https://stackoverflow.com/a/23551356/1445661 – mao47 Mar 14 '18 at 17:00
  • I need the function with some recursion, My Class (Say Order) has property with Object being of another class (Say Product) & that class (Products) has property being of another class (Say Dimensions) ... Current function doesn't add columns for properties of classes (Product & Dimensions) but only Orders. – Mayank Parmar Jan 20 '20 at 11:29
  • @HarshilRaval I think we can't use this method like the way you mentioned because it is not an extension method. – Zeeshanef Jun 17 '21 at 11:59
  • This class does not work at all. I wonder why he got so many points? Each class I give as input returns only the value NULL. – گلی Jul 28 '21 at 08:23
  • For me it works if I add "this" before List. public static DataTable ToDataTable(this List items) – devielu Jul 30 '21 at 10:31
19

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }
Ehsan
  • 31,833
  • 6
  • 56
  • 65
-1
private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
r.vengadesh
  • 1,721
  • 3
  • 20
  • 36
  • 3
    `ConvertListToDataTable(...);` is not known in dotnet unless you visit this page where you can find code for this method `http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list- – Bellash Feb 11 '14 at 08:51