Photo Gallery

Wednesday, January 31, 2018

Generic List Collection to DataTable using Extension Method

In this tutorial, we will see how to convert generic list collection into data table with the help of extension method and i will ensure you that by using this code/ class  you can able to do it with minimum changes in your class file.


/// <summary>
/// This extension method used to convert your list of Generic type into data table.
/// </summary>
public static DataTable ToDataTable<T>(this 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;
}



If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below.

Thank you

No comments:

Post a Comment