While working on Asp.Net project I got the requirement to convert List of string into datatable. Suppose there is a list of countries.
Let’s create an example to convert list of string into datatable for demonstration purpose.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
protected void Page_Load(object sender, EventArgs e)
{
List<string> countries = new List<string>();
countries.Add("USA");
countries.Add("INDIA");
countries.Add("JAPAN");
countries.Add("CHINA");
countries.Add("ENGLAND");
DataTable dt = ListToDataTable(countries);
}
public static DataTable ListToDataTable<T>(IList<T> thisList)
{
DataTable dt = new DataTable();
if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
{
DataColumn dc = new DataColumn("CountryList");
dt.Columns.Add(dc);
foreach (T item in thisList)
{
DataRow dr = dt.NewRow();
dr[0] = item;
dt.Rows.Add(dr);
}
}
else
{
PropertyInfo[] propertyInfo = typeof(T).GetProperties();
foreach (PropertyInfo pi in propertyInfo)
{
DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
dt.Columns.Add(dc);
}
for (int item = 0; item < thisList.Count(); item++)
{
DataRow dr = dt.NewRow();
for (int property = 0; property < propertyInfo.Length; property++)
{
dr[property] = propertyInfo[property].GetValue(thisList[item], null);
}
dt.Rows.Add(dr);
}
}
dt.AcceptChanges();
return dt;
}