C# DataTable转List对应Model集合

public static List<T> ToList<T>(DataTable dt)
{//转载请保留 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;
}

评论