DataTable与List互转通用类

pub­lic sta­t­ic class DataT­able­Helper
{
/// /// 将datat­able转换为泛型集合 ///
///
///
///
pub­lic sta­t­ic List ToList(this DataT­able input­DataT­able) where TEn­ti­ty : class, new()
{
if (input­DataT­able == null)
{
throw new ArgumentNullException(“input datat­able is null”);
}
Type type = typeof(TEntity);
Prop­er­ty­In­fo[] prop­er­ty­In­fos = type.GetProperties();
List lstEn­ti­tys = new List();
fore­ach (DataRow row in inputDataTable.Rows)
{
object obj = Activator.CreateInstance(type);
fore­ach (Prop­er­ty­In­fo pro in prop­er­ty­In­fos)
{
fore­ach (Dat­a­Col­umn col in inputDataTable.Columns)
{
//如果直接查询的数据库,数据库是不区别大小写的,所以转换为小写忽略大小写的问题
if (col.ColumnName.ToLower().Equals(pro.Name.ToLower()))
{
//属性是否是可写的,如果是只读的属性跳过。
if (pro.CanWrite)
{
//判断类型,基本类型,如果是其他的类属性
if (pro.PropertyType == typeof(System.Int32))
{
pro.SetValue(obj, Convert.ToInt32(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.String))
{
pro.SetValue(obj, row[pro.Name.ToLower()].ToString());
}
else if (pro.PropertyType == typeof(System.Boolean))
{
pro.SetValue(obj, Convert.ToBoolean(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.DateTime))
{
pro.SetValue(obj, Convert.ToDateTime(row[pro.Name.ToLower()]));
}
else if (pro.PropertyType == typeof(System.Int64))
{
pro.SetValue(obj, Convert.ToInt64(row[pro.Name.ToLower()]));
}
else
{
pro.SetValue(obj, row[pro.Name.ToLower()]);
}

        
///          /// DataTable转成List         /// 
         public static List ToDataList(this DataTable dt)
         {
             var list = new List();
             var plist = new List(typeof(T).GetProperties()); 
        if (dt == null || dt.Rows.Count == 0)
        {
            return null;
        }

        foreach (DataRow item in dt.Rows)
        {
            T s = Activator.CreateInstance<T>();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                if (info != null)
                {
                    try
                    {
                        if (!Convert.IsDBNull(item[i]))
                        {
                            object v = null;
                            if (info.PropertyType.ToString().Contains("System.Nullable"))
                            {
                                v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                            }
                            else
                            {
                                v = Convert.ChangeType(item[i], info.PropertyType);
                            }
                            info.SetValue(s, v, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                    }
                }
            }
            list.Add(s);
        }
        return list;
    }

    /// <summary>
    /// DataTable转成实体对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static T ToDataEntity<T>(this DataTable dt)
    {
        T s = Activator.CreateInstance<T>();
        if (dt == null || dt.Rows.Count == 0)
        {
            return default(T);
        }
        var plist = new List<PropertyInfo>(typeof(T).GetProperties());
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
            if (info != null)
            {
                try
                {
                    if (!Convert.IsDBNull(dt.Rows[0][i]))
                    {
                        object v = null;
                        if (info.PropertyType.ToString().Contains("System.Nullable"))
                        {
                            v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
                        }
                        else
                        {
                            v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
                        }
                        info.SetValue(s, v, null);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                }
            }
        }
        return s;
    }

    /// <summary>
    /// List转成DataTable
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entities">实体集合</param>
    public static DataTable ToDataTable<T>(List<T> entities)
    {
        if (entities == null || entities.Count == 0)
        {
            return null;
        }

        var result = CreateTable<T>();
        FillData(result, entities);
        return result;
    }

    /// <summary>
    /// 创建表
    /// </summary>
    private static DataTable CreateTable<T>()
    {
        var result = new DataTable();
        var type = typeof(T);
        foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            var propertyType = property.PropertyType;
            if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                propertyType = propertyType.GetGenericArguments()[0];
            result.Columns.Add(property.Name, propertyType);
        }
        return result;
    }

    /// <summary>
    /// 填充数据
    /// </summary>
    private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
    {
        foreach (var entity in entities)
        {
            dt.Rows.Add(CreateRow(dt, entity));
        }
    }

    /// <summary>
    /// 创建行
    /// </summary>
    private static DataRow CreateRow<T>(DataTable dt, T entity)
    {
        DataRow row = dt.NewRow();
        var type = typeof(T);
        foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
        }
        return row;
    }
          }
                    }
                }
            }
            TEntity tEntity = obj as TEntity;
            lstEntitys.Add(tEntity);
        }
        return lstEntitys;
    }
     
    /// <summary>
    /// 将list转换为datatable
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="inputList"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<TEntity>(this List<TEntity> inputList) where TEntity : class, new()
    {
        if (inputList == null)
        {
            throw new ArgumentNullException("inputList");
        }
        DataTable dt = null;
        Type type = typeof(TEntity);
        if (inputList.Count == 0)
        {
            dt = new DataTable(type.Name);
            return dt;
        }
        else { dt = new DataTable(); }
        PropertyInfo[] propertyInfos = type.GetProperties();
        foreach (var item in propertyInfos)
        {
            dt.Columns.Add(new DataColumn() { ColumnName = item.Name, DataType = item.PropertyType });
        }
        foreach (var item in inputList)
        {
            DataRow row = dt.NewRow();
            foreach (var pro in propertyInfos)
            {
                row[pro.Name] = pro.GetValue(item);
            }
            dt.Rows.Add(row);
        }
        return dt;
    }

为您推荐

发表评论

您的电子邮箱地址不会被公开。