C# DataTable转List对应Model集合,DataRow转Model

2021-09-21 更新
public static List<T> ToList<T>(DataTable dt)
{
    try
    {
        //转载请保留 http://www.luofenming.com/show.aspx?id=ART2019120700001
        List<T> list = new List<T>();
        Type t = typeof(T);
        List<PropertyInfo> plist = new List<PropertyInfo>(typeof(T).GetProperties());
        if (dt != null)
        {
            foreach (DataRow item in dt.Rows)
            {//如果是单行转对应Model只要这一部分
                T s = System.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)
                    {
                        if (!Convert.IsDBNull(item[i]))
                        {
                            info.SetValue(s, item[i], null);
                        }
                    }
                }
                list.Add(s);
            }
        }
        return list;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}
/// <summary>
/// 将DataRow转换成实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
private static T GetItem<T>(DataRow dr)
{
    try
    {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance<T>();
        foreach (DataColumn column in dr.Table.Columns)
        {
            foreach (PropertyInfo pro in temp.GetProperties())
            {
                if (pro.Name.ToLower() == column.ColumnName.ToLower())
                {
                    if (dr[column.ColumnName] == DBNull.Value)
                    {
                        pro.SetValue(obj, " ", null);
                        break;
                    }
                    else
                    {
                        pro.SetValue(obj, dr[column.ColumnName], null);
                        break;
                    }
                }
            }
        }
        return obj;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}
视频讲解地址 https://www.bilibili.com/video/BV1YL4y187qD

评论