List to datatable c#

 In C#, you can convert a List to a DataTable using the following steps:

  1. Create a new DataTable instance with columns matching the properties of the objects in the list.
  2. Loop through the list and create a new DataRow for each object, populating the columns with the property values.
  3. Add each DataRow to the DataTable using the Rows property.
Example:-

public static DataTable ConvertListToDataTable<T>(List<T> list)
{
    // Create a new DataTable instance
    DataTable dataTable = new DataTable();

    // Get the properties of the object type
    PropertyInfo[] properties = typeof(T).GetProperties();

    // Add the columns to the DataTable
    foreach (PropertyInfo property in properties)
    {
        dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
    }

    // Add the rows to the DataTable
    foreach (T item in list)
    {
        DataRow dataRow = dataTable.NewRow();

        foreach (PropertyInfo property in properties)
        {
            dataRow[property.Name] = property.GetValue(item) ?? DBNull.Value;
        }

        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}


This method uses generics to convert any List to a DataTable. You can call this method and pass in your List, like so:

List<MyObject> myList = GetMyList(); // Get your list from wherever
DataTable myDataTable = ConvertListToDataTable<MyObject>(myList);

Popular Posts