DataTableSerializer datatable序列化成对象 datatable to entity serialization

public class DataTableSerializer
{
  public static List ToList(DataTable dt)
  {
    var list = new List();
    if (dt == null || dt.Rows.Count == 0)
      return list;//return empty list instead of null object
    list.AddRange(from DataRow row in dt.Rows select ToEntity(row));
    return list;
  }
  public static T ToEntity( DataRow row)
  {
    var objType = typeof(T);
    var obj = Activator.CreateInstance();
    foreach (DataColumn column in row.Table.Columns)
    {
      var property = objType.GetProperty(column.ColumnName,
          BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
      if (property == null || !property.CanWrite)
      {
        continue;
      }
      var value = row[column.ColumnName];
      if (value == DBNull.Value)
      {
        value = null;
      }
      else
      {
        //add what you need.
        //if (column.DataType == typeof (DateTime))
        //{
        //    value = ((DateTime)value).ToString("yyyy-MM-dd");
        //}
      }
      property.SetValue(obj, value, null);
    }
    return obj;
  }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注