1 ///2 /// DataSet转换为实体类 3 /// 4 ///实体类 5 /// DataSet 6 /// 待转换数据表索引 7 ///实体类 8 public static T DataSetToEntity(DataSet p_DataSet, int p_TableIndex) 9 {10 if (p_DataSet == null || p_DataSet.Tables.Count < 0)11 return default(T);12 if (p_TableIndex > p_DataSet.Tables.Count - 1)13 return default(T);14 if (p_TableIndex < 0)15 p_TableIndex = 0;16 if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)17 return default(T);18 19 DataRow p_Data = p_DataSet.Tables[p_TableIndex].Rows[0];20 // 返回值初始化21 T _t = (T)Activator.CreateInstance(typeof(T));22 PropertyInfo[] propertys = _t.GetType().GetProperties();23 foreach (PropertyInfo pi in propertys)24 {25 if (p_DataSet.Tables[p_TableIndex].Columns.IndexOf(pi.Name.ToUpper()) != -1 && p_Data[pi.Name.ToUpper()] != DBNull.Value)26 {27 pi.SetValue(_t, p_Data[pi.Name.ToUpper()], null);28 }29 else30 {31 pi.SetValue(_t, null, null);32 }33 }34 return _t;35 }36 37 /// 38 /// DataSet转换为实体列表39 /// 40 ///实体类 41 /// DataSet42 /// 待转换数据表索引43 ///实体类列表 44 public static IListDataSetToEntityList (DataSet p_DataSet, int p_TableIndex)45 {46 if (p_DataSet == null || p_DataSet.Tables.Count < 0)47 return default(IList );48 if (p_TableIndex > p_DataSet.Tables.Count - 1)49 return default(IList );50 if (p_TableIndex < 0)51 p_TableIndex = 0;52 if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)53 return default(IList );54 55 DataTable p_Data = p_DataSet.Tables[p_TableIndex];56 // 返回值初始化57 IList result = new List ();58 for (int j = 0; j < p_Data.Rows.Count; j++)59 {60 T _t = (T)Activator.CreateInstance(typeof(T));61 PropertyInfo[] propertys = _t.GetType().GetProperties();62 foreach (PropertyInfo pi in propertys)63 {64 if (p_Data.Columns.IndexOf(pi.Name.ToUpper()) != -1 && p_Data.Rows[j][pi.Name.ToUpper()] != DBNull.Value)65 {66 pi.SetValue(_t, p_Data.Rows[j][pi.Name.ToUpper()], null);67 }68 else69 {70 pi.SetValue(_t, null, null);71 }72 }73 result.Add(_t);74 }75 return result;76 }