DataTable convert to List
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace ifabTableToList
{
public class ifabTableToList
{
public static List<T> Convert<T>(DataTable dt) where T : class
{
try
{
if (dt == null || dt.Rows.Count == 0)
return null;
T cls = Activator.CreateInstance(typeof(T)) as T;
var proInfo = cls.GetType().GetProperties();
List <T> lsObj = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
cls = Activator.CreateInstance(typeof(T)) as T;
foreach (var item in proInfo)
{
cls.GetType().GetProperty(item.Name).SetValue(cls,
System.Convert.ChangeType(dt.Rows[i][item.Name], item.PropertyType), null);
}
lsObj.Add(cls);
}
return lsObj;
}
catch (Exception ex)
{
throw;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace ifabTableToList
{
public class ifabTableToList
{
public static List<T> Convert<T>(DataTable dt) where T : class
{
try
{
if (dt == null || dt.Rows.Count == 0)
return null;
T cls = Activator.CreateInstance(typeof(T)) as T;
var proInfo = cls.GetType().GetProperties();
List <T> lsObj = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
cls = Activator.CreateInstance(typeof(T)) as T;
foreach (var item in proInfo)
{
cls.GetType().GetProperty(item.Name).SetValue(cls,
System.Convert.ChangeType(dt.Rows[i][item.Name], item.PropertyType), null);
}
lsObj.Add(cls);
}
return lsObj;
}
catch (Exception ex)
{
throw;
}
}
}
}
留言
張貼留言