首页 > 代码库 > 泛型集合的运用

泛型集合的运用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/// <summary>
  /// DataSet装换为泛型集合
  /// </summary>
  /// <typeparam name="T">泛型</typeparam>
  /// <param name="p_DataSet">DataSet</param>
  /// <param name="p_TableIndex">待转换数据表索引</param>
  /// <returns>泛型集合</returns>
  private static IList<T> DataSetToIList<T>(DataSet p_DataSet, int p_TableIndex)
  {
      if (p_DataSet == null || p_DataSet.Tables.Count < 0)
          return null;
      if (p_TableIndex > p_DataSet.Tables.Count - 1)
          return null;
      if (p_TableIndex < 0)
          p_TableIndex = 0;
      if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)
          return null;
 
      DataTable p_Data = http://www.mamicode.com/p_DataSet.Tables[p_TableIndex];
      // 返回值初始化
      IList<T> result = new List<T>();
      for (int j = 0; j < p_Data.Rows.Count; j++)
      {
          T _t = (T)Activator.CreateInstance(typeof(T));
          PropertyInfo[] propertys = _t.GetType().GetProperties();
          foreach (PropertyInfo pi in propertys)
          {
              for (int i = 0; i < p_Data.Columns.Count; i++)
              {
                  // 属性与字段名称一致的进行赋值
                  if (pi.Name.ToLower().Equals(p_Data.Columns[i].ColumnName.ToLower()))
                  {
                      // 数据库NULL值单独处理
                      if (p_Data.Rows[j][i] != DBNull.Value)
                      {
                          //if (p_Data.Rows[j][i] is byte[])
                          //{
                          //    byte[] bytes = (byte[])p_Data.Rows[j][i];
                          //    MemoryStream ms = new MemoryStream(bytes);
                          //    Image img = Image.FromStream(ms);
                          //    pi.SetValue(_t, img, null);
                          //    continue;
                          //}
                          pi.SetValue(_t, p_Data.Rows[j][i], null);
                      }
                      else
                          pi.SetValue(_t, null, null);
                      break;
                  }
              }
          }
          result.Add(_t);
      }
      return result;
  }