Datatable is used since the invention of ADO.Net and this object is very useful to carry data all along the application. As development phase goes forward, LINQ come in picture..now a days LINQ is used in almost every second application, but sometime we have requirement that we have data in LINQ but want it in datatable, we can easily convert from LINQ to DT with the help of reflection as:
/// <summary>
/// Convert LINQ Output to Datatable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="varlist"></param>
/// <returns></returns>
private DataTable ConvertLINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtTest = new DataTable();
// column names
System.Reflection.PropertyInfo[] oProps = null;
if (varlist == null) return dtTest;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table,
//Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtTest.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtTest.NewRow();
foreach (System.Reflection.PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null
? DBNull.Value : pi.GetValue
(rec, null);
}
dtTest.Rows.Add(dr);
}
return dtTest;
}
Cheers!!!!!!!!!!!!!!!!!!!!!
Comments
Post a Comment