c#拓展方法將datatable轉換成實體
阿新 • • 發佈:2018-12-06
- /// <summary>
- /// DataTable 轉換為 List<T>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static List<T> ToList<T>(this DataTable dt) where T : class,new()
- {
- Type t = typeof(T);
- PropertyInfo[] propertys = t.GetProperties();
- List<T> lst = new List<T>();
- string typeName = string.Empty;
- foreach (DataRow dr in dt.Rows)
- {
- T entity = new T();
- foreach (PropertyInfo pi in propertys)
- {
- typeName = pi.Name;
- if (dt.Columns.Contains(typeName))
- {
- if (!pi.CanWrite) continue;
- object value = dr[typeName];
- if (value == DBNull.Value) continue;
- if (pi.PropertyType == typeof(string))
- {
- pi.SetValue(entity, value.ToString(), null);
- }
- else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
- {
- pi.SetValue(entity, int.Parse(value.ToString()), null);
- }
- else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
- {
- pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
- }
- else if (pi.PropertyType == typeof(float) || pi.PropertyType == typeof(float?))
- {
- pi.SetValue(entity, float.Parse(value.ToString()), null);
- }
- else if (pi.PropertyType == typeof(double) || pi.PropertyType == typeof(double?))
- {
- pi.SetValue(entity, double.Parse(value.ToString()), null);
- }
- else if (pi.PropertyType == typeof(byte) || pi.PropertyType == typeof(byte?))
- {
- pi.SetValue(entity, byte.Parse(value.ToString()), null);
- }
- else if (pi.PropertyType == typeof(Int16) || pi.PropertyType == typeof(Int16?))
- {
- pi.SetValue(entity, Int16.Parse(value.ToString()), null);
- }
- else
- {
- pi.SetValue(entity, value, null);
- }
- }
- }
- lst.Add(entity);
- }
- return lst;
- }