泛型与DataTable的互相转化

///DataTable到范型转换
/// <summary>
/// 适合于实体类和DataTable对应的情况
/// </summary>
//将泛型类转换成DataTable  
 
public static DataTable ToDataTable<T>(List<T> entitys)
    {        DataTable dtResult = new DataTable();
        if (entitys == null || entitys.Count < 1)
        {
            throw new Exception(”需转换的集合为空”);
        }
        Type entityType = entitys[0].GetType();


        List<PropertyInfo> propertyInfoList = entityType.GetProperties().ToList<PropertyInfo>;();
        foreach (PropertyInfo item in propertyInfoList) 
       {
            dtResult.Columns.Add(new DataColumn(item.Name, item.PropertyType));
        }
        foreach (T entity in entitys)
        {
            DataRow dr = dtResult.NewRow();
            foreach (PropertyInfo item in propertyInfoList)
            {
                dr[item.Name] = item.GetValue(entity, null);
            }
            dtResult.Rows.Add(dr);
        }
        return dtResult;
    }

    //将泛型类转换成DataTable
    public static IList<T> ToList<T>(DataTable dt)
    {
        List<T> list = new List<T>();
        //T model = default(T);
        for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
        {
            DataRow dr = dt.Rows[iRow];
            T t = (T)System.Activator.CreateInstance(typeof(T));
            List<PropertyInfo> listPropertyInfo = t.GetType().GetProperties().ToList<PropertyInfo>();
            foreach (PropertyInfo item in listPropertyInfo)
            {
                if (dr[item.Name] != DBNull.Value)
                {
                    item.SetValue(t, dr[item.Name], null);
                }
                else
                {
                    item.SetValue(t, (string)null, null);
                }
            }
            list.Add(t);
        }
        return list;
    }
}

分享这个帖子:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

没有评论 to “泛型与DataTable的互相转化”

留下评论:

昵称(必须):
邮箱地址 (不会被公开) (必须):
站点
评论 (必须)
XHTML: 您可以使用这些标记: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">