將dataset,reader轉化爲IList

將dataset轉化爲IList<T>,關鍵是將datatable轉化爲類型IList<T>,代碼如下:

public T Export(System.Data.DataTable Table)
        {
            // 定義集合
            IList<T> List = null;
            // 獲得此模型的類型
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in Table.Rows)
            {
                T t = new T();
                //獲得此模型的公共屬性
                PropertyInfo[] propertys = t.GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    //檢查DataTable是否包含此列
                    if (Table.Columns.Contains(tempName))
                    {
                        // 判斷此屬性是否有Setter
                        if (!pi.CanWrite)
                        {
                            continue;
                        }
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            if (value.GetType().ToString() == "System.Double")
                            {
                                pi.SetValue(t, doubleToInt(value), null);
                            }
                            else if (value.GetType().ToString() == "System.String")
                            {
                                pi.SetValue(t, value, null);
                            }
                        }
                    }
                }
                return t;
            }
        }

 

 

 

 

public static IList <T> FillList <T>(System.Data.IDataReader reader)

        {

            IList <T> lst= new List <T>();

            while (reader.Read())

            {

                  T RowInstance = Activator.CreateInstance <T>();

                foreach (PropertyInfo Property in typeof(T).GetProperties())

                {

                    foreach (BindingFieldAttribute FieldAttr in    Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))

                  {

                  try

                    {

  int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);

                          if (reader.GetValue(Ordinal) != DBNull.Value)

                          {

                                Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);

                            }

                        }

                        catch

                        {

                            break;

                        }

                    }

                }

                lst.Add(RowInstance);

            }

            return lst;

        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章