当前位置:Gxlcms >
数据库问题 >
读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
时间:2021-07-01 10:21:17
帮助过:3人阅读
/// <summary>
2 /// 获取UserInfo泛型集合
3 /// </summary>
4 /// <param name="connStr">数据库连接字符串</param>
5 /// <param name="sqlStr">要查询的T-SQL</param>
6 /// <returns></returns>
7 public IList<UserInfo> GetUserInfoAll(
string connStr,
string sqlStr)
8 {
9 using (SqlConnection conn =
new SqlConnection(connStr))
10 {
11 using (SqlCommand cmd =
new SqlCommand(sqlStr, conn))
12 {
13 SqlDataReader sdr =
cmd.ExecuteReader();
14
15 IList<UserInfo> list =
new List<UserInfo>
();
16
17 while (sdr.Read())
18 {
19
20 UserInfo userInfo =
new UserInfo();
21
22 userInfo.ID = (Guid)sdr[
"ID"];
23
24 userInfo.LoginName = sdr[
"LoginName"].ToString();
25
26 userInfo.LoginPwd = sdr[
"LoginPwd"].ToString();
27
28 list.Add(userInfo);
29
30 }
31 return list;
32 }
33 }
34 }
35
36 /// <summary>
37 /// 获取泛型集合
38 /// </summary>
39 /// <typeparam name="T">类型</typeparam>
40 /// <param name="connStr">数据库连接字符串</param>
41 /// <param name="sqlStr">要查询的T-SQL</param>
42 /// <returns></returns>
43 public IList<T> GetList<T>(
string connStr,
string sqlStr)
44 {
45 using (SqlConnection conn =
new SqlConnection(connStr))
46 {
47 using (SqlDataAdapter sda =
new SqlDataAdapter(sqlStr, conn))
48 {
49 DataSet ds =
new DataSet();
50 sda.Fill(ds);
51 return DataSetToList<T>(ds,
0);
52 }
53 }
54 }
55
56 /// <summary>
57 /// DataSetToList
58 /// </summary>
59 /// <typeparam name="T">转换类型</typeparam>
60 /// <param name="dataSet">数据源</param>
61 /// <param name="tableIndex">需要转换表的索引</param>
62 /// <returns></returns>
63 public IList<T> DataSetToList<T>(DataSet dataSet,
int tableIndex)
64 {
65 //确认参数有效
66 if (dataSet ==
null || dataSet.Tables.Count <=
0 || tableIndex <
0)
67 return null;
68
69 DataTable dt =
dataSet.Tables[tableIndex];
70
71 IList<T> list =
new List<T>
();
72
73 for (
int i =
0; i < dt.Rows.Count; i++
)
74 {
75 //创建泛型对象
76 T _t = Activator.CreateInstance<T>
();
77 //获取对象所有属性
78 PropertyInfo[] propertyInfo =
_t.GetType().GetProperties();
79 for (
int j =
0; j < dt.Columns.Count; j++
)
80 {
81 foreach (PropertyInfo info
in propertyInfo)
82 {
83 //属性名称和列名相同时赋值
84 if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
85 {
86 if (dt.Rows[i][j] !=
DBNull.Value)
87 {
88 info.SetValue(_t, dt.Rows[i][j],
null);
89 }
90 else
91 {
92 info.SetValue(_t,
null,
null);
93 }
94 break;
95 }
96 }
97 }
98 list.Add(_t);
99 }
100 return list;
101 }
public class UserInfo
{
public System.Guid ID { get; set; }
public string LoginName { get; set; }
public string LoginPwd { get; set; }
}
读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
标签: