datatable 转 对象

Posted 张小帅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了datatable 转 对象相关的知识,希望对你有一定的参考价值。

private static List<T> ConvertToList<T>(DataTable dt)
  where T : new()
  {
   T t1;
   Type type = typeof(T);
   List<T> list = new List<T>();
   PropertyInfo[] propertys = type.GetProperties();
   string name = string.Empty;
   foreach (DataRow dr in dt.Rows)
   {
    T t2 = default(T);
    if (t2 == null)
    {
     t1 = Activator.CreateInstance<T>();
    }
    else
    {
     t2 = default(T);
     t1 = t2;
    }
    T t = t1;
    PropertyInfo[] propertyInfoArray = propertys;
    for (int i = 0; i < (int)propertyInfoArray.Length; i++)
    {
     PropertyInfo pi = propertyInfoArray[i];
     name = pi.Name;
     if (dt.Columns.Contains(name))
     {
      if (!pi.CanWrite)
      {
                            continue;
      }
      object value = SqlHelper.ToCSharpValue(dr[name]);
      if (null != value)
      {
       pi.SetValue(t, value, null);
      }
     }
    
    }
    list.Add(t);
   }
   return list;
  }

以上是关于datatable 转 对象的主要内容,如果未能解决你的问题,请参考以下文章

DataTable转实体类

c#list与datatable 用哪个

求问 C#如何将json字符串转为datatable 求详细解答

DataTable转Json Json转DataTable

NPOI DataTable转Excel ,Excel转DataTable

c# DataTable转List 和 List转 DataTable