任意List 和DatabTable的转换

 public static IEnumerable<T> ToEntityList<T>(this DataTable table) where T : class
        {
            var entityList = new List<T>();
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    var entity = (T)Activator.CreateInstance(typeof(T));
                    for (int i = 0; i < dr.Table.Columns.Count; i++)
                    {
                        PropertyInfo propertyInfo = entity.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                        if (propertyInfo != null && dr[i] != DBNull.Value)
                        {
                            propertyInfo.SetValue(entity, dr[i], null);
                        }
                    }
                    entityList.Add(entity);
                }
            }
            return entityList;
        }
posted @ 2016-11-19 10:24  晓明的哥哥  阅读(399)  评论(1编辑  收藏  举报