//////////// Using NameSpace
using System.Reflection;
//////////////////// Class
public class Employee
{
public int EmpId{ get; set; }
public string EmpName { get; set;}
}
public void fill_data()
{
DataTable dt = new DataTable();
List<Employee> lstMembership = Convert_ToList<Employee>(dt);
}
///////////// DBHelper
public static List<T> Convert_ToList<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = Get_Items<T>(row);
data.Add(item);
}
return data;
}
private static T Get_Items<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pInfo in temp.GetProperties())
{
if (pInfo.Name == column.ColumnName)
pInfo.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
/////////////////////// Using Linq
public static List<T> ConvertToList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName.ToLower()).ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name.ToLower()))
{
try
{
pro.SetValue(objT, row[pro.Name]);
}
catch (Exception ex) { }
}
}
return objT;
}).ToList();
}
No comments:
Post a Comment