首页 > 其他 > 详细

ModelConvertHelper(将DataTable转换成List<model>)

时间:2014-02-25 23:07:24      阅读:722      评论:0      收藏:0      [点我收藏+]

 

public class ModelConvertHelper<T> where T : new()
{
     public static IList<T> ConvertToModel(DataTable dt)
     {
         // Collection definition
         IList<T> ts = new List<T>();

         // Get model type
         Type type = typeof(T);

         string tempName = "";

         foreach (DataRow dr in dt.Rows)
         {
             T t = new T();

             // Get property of model
             PropertyInfo[] propertys = t.GetType().GetProperties();

             foreach (PropertyInfo pi in propertys)
             {
                 tempName = pi.Name;

                 // check column is exsit
                 if (dt.Columns.Contains(tempName))
                 {
                     // Whether can be set value
                     if (!pi.CanWrite) continue;

                     object value = dr[tempName];
                     if (value != DBNull.Value)
                         pi.SetValue(t, value, null);
                 }
             }

             ts.Add(t);
         }

         return ts;
     }
}

ModelConvertHelper(将DataTable转换成List<model>)

原文:http://www.cnblogs.com/key1309/p/3566567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!