I have a task to need to get a DataTable, however, all existing objects are List, I need convert some of those lists to DataTables. Before I wrote my own code to do it. I searched internet and got 2 perfect articles which I need.
1: From DotNet Friends, By patriwala, Convert Generic List In To DataTable
A simple and easy to use one, I adopted this solution.
2: Casting from a Collection to a Data Table using Generics and Attributes by Joseph Finsterwald
Here I copy some code from patriwala’s article:
/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}return tbl;
}/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
And, how to use? Very easy, I show you my own sample:
List<SoldTerritories> listSoldTerritories = GetSoldTerritoriesList();
DataTable dt = ConvertTo<SoldTerritories>(listSoldTerritories);
That is!
