DataTable转成List
//把一个Datatable 赋值给一个List对象
//定义一个转换类
public class ConvertTool
{
public static List<T> DataConvert<T>(DataTable tb)
{
List<T> lst = new List<T>();
DataConvert<T>(tb, ref lst);
return lst;
}
public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst)
{
for (int i = 0; i < tb.Rows.Count; i++)
{
lst.Add(DataConvert<T>(tb.Rows[i]));
}
return lst;
}
public static T DataConvert<T>(DataRow row)
{
var type = typeof(T);
object obj = type.Assembly.CreateInstance(type.FullName);
var c = (T)obj;
DataConvert(row, ref c);
return c;
}
public static T DataConvert<T>(DataRow row, ref T t)
{
var ps = t.GetType().GetProperties();
var tbColumns = row.Table.Columns;
foreach (var c in ps)
{
var colName = c.Name;
if (tbColumns.Contains(colName))
{
object nr = row[colName] == DBNull.Value ? null : row[colName];
if (nr == null)
{
c.SetValue(t, nr, null);
}
else
{
var nrType = c.PropertyType;
if (nrType == typeof(decimal) || nrType == typeof(decimal?))
{
nr = Convert.ToDecimal(nr);
}
else if (nrType == typeof(Int64) || nrType == typeof(Int64?))
{
nr = Convert.ToInt64(nr);
}
else if (nrType == typeof(double) || nrType == typeof(double?))
{
nr = Convert.ToDouble(nr);
}
else if (nrType == typeof(Int32) || nrType == typeof(Int32?))
{
nr = Convert.ToInt32(nr);
}
else if (nrType == typeof(Int16) || nrType == typeof(Int16?))
{
nr = Convert.ToInt16(nr);
}
c.SetValue(t, nr, null);
}
}
}
return t;
}
}
定义一个测试的实体类
多种类型全部用上
public class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Money { get; set; }
public bool IsValid { get; set; }
public DateTime BirthDay { get; set; }
}
方法调用及显示结果
public class Program
{
static void Main(string[] args)
{
//定义一个DataTable 并赋值
DataTable dt = new DataTable("dtTest");
DataColumn dc = null;
dc = dt.Columns.Add("Id", Type.GetType("System.Int32"));
dc = dt.Columns.Add("Name", Type.GetType("System.String"));
dc = dt.Columns.Add("Money", Type.GetType("System.Decimal"));
dc = dt.Columns.Add("IsValid", Type.GetType("System.Boolean"));
dc = dt.Columns.Add("BirthDay", Type.GetType("System.DateTime"));
DataRow newRow;
newRow = dt.NewRow();
newRow["Id"] = "1";
newRow["Name"] = "测试1";
newRow["IsValid"] = true;
newRow["Money"] = 100.00m;
newRow["BirthDay"] = DateTime.Now ;
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow["Id"] = "2";
newRow["Name"] = "测试2";
newRow["IsValid"] = true;
newRow["Money"] = 100.00m;
newRow["BirthDay"] = DateTime.Now;
dt.Rows.Add(newRow);
//调用DataTable转成List
List<TestClass> Li = ConvertTool.DataConvert<TestClass>(dt);
}
}
现在有很多流行的ORM框架,直接取出来对象数据很方便,不用再转。实现原理大同小异;