/// <summary>
/// DataTable转换为List&lt;Model&gt;
/// </summary>
public static class DataTableToListModel<T> where T : new()
{
    public static IList<T> ConvertToModel(DataTable dt)
    {
        //定义集合
        IList<T> ts = new List<T>();
        T t = new T();
        string tempName = "";
        //获取此模型的公共属性
        PropertyInfo[] propertys = t.GetType().GetProperties();
         foreach (DataRow row in dt.Rows)
        {         
            t = new T();
            foreach (PropertyInfo pi in propertys)
            {
                tempName = pi.Name;
                //检查DataTable是否包含此列
                if (dt.Columns.Contains(tempName))
                {
                    //判断此属性是否有set
                    if (!pi.CanWrite)
                        continue;
                    object value = row[tempName];
                    if (value != DBNull.Value)
                        pi.SetValue(t, value, null);
                }
            }
            ts.Add(t);
        }
        return ts;
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案