This extension method lets you convert an array of objects into a DataTable. DataTables are used for SQL inserts.
This solution is not mine, in fact it has been copied so many times that I don’t know who came up with it in the first place.
STEP 1: DEFINE YOUR CLASS
The class must represent the SQL table, INCLUDING THE SORT ORDER OF THE DATABASE FIELDS. If the sort order is not correct, you will not be able to use the DataTable for SQL inserts.
This is just an example of a class. Yours will look different.
public class FavoriteDTO
{
public int RowId { get; set; }
public int UserKey { get; set; }
public string FavoriteId { get; set; }
public DateTime? LastModified { get; set; }
public bool? IsDeleted { get; set; }
public DateTime? Created { get; set; }
}
STEP 2: IMPLEMENT THIS EXTENSION METHOD
using System.ComponentModel;
using System.Data;
namespace MyCode
{
public static class IEnumerableExtensions
{
public static DataTable ToDataTable<T>(this IEnumerable<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;
}
}
}
STEP 3: HOW TO USE THE EXTENSION METHOD
List<FavoriteDTO> favorites = new List<FavoriteDTO>();
favorites.Add(new FavoriteDTO() { RowId = 0, UserKey = 4 });
favorites.Add(new FavoriteDTO() { RowId = 1, UserKey = 2 });
favorites.Add(new FavoriteDTO() { RowId = 2, UserKey = 0 });
favorites.Add(new FavoriteDTO() { RowId = 3, UserKey = 6 });
favorites.Add(new FavoriteDTO() { RowId = 3, UserKey = 9 });
var dataTable = favorites.ToDataTable();
That’s it. Happy coding.
MORE TO READ:
- Sql Bulk Copy/Insert in C# from StackOverflow
- How to Convert a List of Class Objects into DataTable in C# from Automation Curry Puff
- Converting a List to Datatable from MSDN
- DataTable In C# from C# Corner