Monday, April 2, 2012

Convert a generic list to DataTable in C#

The below extension method will help us to convert a generic list to DataTable


public static class DataTableExtension
{
public static DataTable ToDataTable(this List list)
{
Type type = typeof(T);
DataTable dt = new DataTable(type.Name);

var propertyInfos = type.GetProperties().ToList();

//For each property of generic List (T), add a column to table
propertyInfos.ForEach(propertyInfo =>
{
Type columnType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
dt.Columns.Add(propertyInfo.Name, columnType);
});


//Visit every property of generic List (T) and add each value to the data table
list.ForEach(item =>
{
DataRow row = dt.NewRow();
propertyInfos.ForEach(
propertyInfo =>
row[propertyInfo.Name] = propertyInfo.GetValue(item, null) ?? DBNull.Value
);
dt.Rows.Add(row);
});

//Return the datatable
return dt;
}
}




How to use this?




class Program
{
static void Main(string[] args)
{
List lstString = new List();
Enumerable.Range(1, 10).ToList().ForEach(i => lstString.Add(
new Person { PersonId = i
, PersonName = string.Concat("Name", i)
, Sex = i%2 ==0 ? "M":"F"
, Salary = 100 + i
}));

var res = lstString.ToDataTable();
}
}

public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
public string Sex { get; set; }
public decimal Salary { get; set; }
}