DataTable 类型与 List<T> 类型互转

DataTable 数据类型转为List<T>类型,包含可空类型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using System.Globalization;
using System.ComponentModel;

/// <summary>
/// 数据DataTable转化为List(可空类型的转化)
/// </summary>
public partial class test6 : System.Web.UI.Page
{
    SqlHelper sqlhelp = new SqlHelper();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string strSql = "SELECT * FROM TStudent";
        DataSet ds = sqlhelp.ExecuteQuery(sqlhelp.ConnectionStringLocalTransaction, CommandType.Text, strSql);
        IList<testClass> list = DataTableToList<testClass>(ds.Tables[0]);
    }

    /// <summary>
    /// DataTableToList
    /// </summary>
    /// <typeparam name="T">转换类型</typeparam>
    /// <param name="dt">数据源</param>
    /// <returns>泛型集合</returns>
    public IList<T> DataTableToList<T>(DataTable dt)
    {
        IList<T> list = new List<T>();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            //创建泛型对象
            T _t = Activator.CreateInstance<T>();

            //获取对象所有属性
            PropertyInfo[] propertyInfo = _t.GetType().GetProperties();

            for (int j = 0; j < dt.Columns.Count; j++)
            {
                foreach (PropertyInfo info in propertyInfo)
                {
                    //属性名称和列名相同时赋值
                    if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
                    {
                        if (dt.Rows[i][j] != DBNull.Value)
                        {
                            //info.SetValue(_t, dt.Rows[i][j], null);
                            info.SetValue(_t, testClass2.UDChangeType(dt.Rows[i][j], info.PropertyType), null);
                        }
                        else
                        {
                            info.SetValue(_t, null, null);
                        }

                        break;
                    }
                }
            }
            list.Add(_t);
        }
        return list;
    }  
}

public class testClass
{
    public Guid ID { get; set; }
    public int? BOMId { get; set; }
    public int? VALUE { get; set; }
    public DateTime? AddDate { get; set; }
    public string name { get; set; }
}

public static class testClass2 {
    public static object UDChangeType(this object value, Type convertsionType)
    {
        //判断convertsionType类型是否为泛型,因为nullable是泛型类,
        if (convertsionType.IsGenericType &&
            //判断convertsionType是否为nullable泛型类
            convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null || value.ToString().Length == 0)
            {
                return null;
            }

            //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
            NullableConverter nullableConverter = new NullableConverter(convertsionType);
            //将convertsionType转换为nullable对的基础基元类型
            convertsionType = nullableConverter.UnderlyingType;
        }
        return Convert.ChangeType(value, convertsionType);
    }

    public static T ConvertTo<T>(this IConvertible convertibleValue)
    {
        if (null == convertibleValue)
        {
            return default(T);
        }
        if (!typeof(T).IsGenericType)
        {
            return (T)Convert.ChangeType(convertibleValue, typeof(T));
        }
        else
        {
            Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
            if (genericTypeDefinition == typeof(Nullable<>))
            {
                return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
            }
        }
        throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".", convertibleValue.GetType().FullName, typeof(T).FullName));
    }
}
View Code

 List<T> 转化DataTable

    /// <summary>
    /// 根据实体类得到表结构
    /// </summary>
    /// <param name="model">实体类</param>
    /// <returns></returns>
    private DataTable CreateData<T>(T model)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);
        foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
        {
           dataTable.Columns.Add(new DataColumn(propertyInfo.Name, typeof(string)));
           //dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
        }
        return dataTable;
    }
    /// <summary>
    /// 实体类转换成DataTable
    /// 调用示例:DataTable dt= FillDataTable(Entitylist.ToList());
    /// </summary>
    /// <param name="modelList">实体类列表</param>
    /// <returns></returns>
    private DataTable FillDataTable<T>(List<T> modelList)
    {
        if (modelList == null || modelList.Count == 0)
        {
            return null;
        }
        DataTable dt = CreateData(modelList[0]);//创建表结构

        foreach (T model in modelList)
        {
            DataRow dataRow = dt.NewRow();
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                object result = propertyInfo.GetValue(model, null);
                if (result==null)
                {
                    dataRow[propertyInfo.Name] = DBNull.Value;
                }
                else
                {
                    dataRow[propertyInfo.Name] = result;
                }
            }
            dt.Rows.Add(dataRow);
        }
        return dt;
    }
实体类转DataTable

 

posted on 2014-08-14 14:45  二狗你变了  阅读(624)  评论(0)    收藏  举报

导航