首页 > 代码库 > 任意List 和DatabTable的转换

任意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;
        }

任意List 和DatabTable的转换