如何對DataSet進行強類型化
在項目中經常需要用到DataSet來存放數據,但是一直覺得從數據集中獲取數據使用是一件很難受的事情,特別是當需要用到強類型數據的時候,就想到了動手寫個方法來實現。
- /// <summary>
- /// 將數據集強類型化
- /// </summary>
- /// <typeparam name="T">轉換類型</typeparam>
- /// <param name="dataSet">數據源</param>
- /// <param name="tableIndex">需要轉換表的索引</param>
- /// <returns>泛型集合</returns>
- public static IList<T> ToList<T>(this DataSet dataSet, int tableIndex)
- {
- //確認參數有效
- if (dataSet == null || dataSet.Tables.Count <= 0 || tableIndex < 0)
- return null;
- DataTable dt = dataSet.Tables[tableIndex];
- IList<T> list = new List<T>();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- //創建泛型對象
- T _t = Activator.CreateInstance<T>();
- //獲取對象所有屬性
- PropertyInfo[] propertyInfo = _t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- foreach (PropertyInfo info in propertyInfo)
- {
- //屬性名稱和列名相同時賦值
- if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
- {
- if (dt.Rows[i][j] != DBNull.Value)
- {
- info.SetValue(_t, dt.Rows[i][j].ConvertDataTo(info.PropertyType), null);
- }
- else
- {
- info.SetValue(_t, null, null);
- }
- break;
- }
- }
- }
- list.Add(_t);
- }
- return list;
- }
在需要給屬性賦值的時候,為了避免數據集中的字段名與用戶定義的Model屬性名一致而類型不一致的問題,我又寫了個方法,用來把對象進行類型轉換:
- public static object ConvertDataTo(this object obj,Type type)
- {
- if (obj.GetType().Equals(type))
- {
- return obj;
- }
- else
- {
- try
- {
- if (type == typeof(string)) { return obj.ToString(); }
- MethodInfo parseMethod = null;
- foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
- {
- if (mi.Name == "Parse" && mi.GetParameters().Length == 1)
- { parseMethod = mi; break; }
- }
- if (parseMethod == null)
- {
- return null;
- }
- return parseMethod.Invoke(null, new object[] { obj });
- }
- catch
- {
- return null;
- throw;
- }
- }
- }
其實這么寫是比較偷懶的寫法,用了這么多反射, 于是想到做一下性能測試,我建的MVC項目,看一下測試結果:
- public ActionResult Index()
- {
- DataSet ds = new DataSet();
- DataTable dt = new DataTable();
- dt.Columns.Add("resourcename1", typeof(string));
- dt.Columns.Add("resourcename2", typeof(string));
- dt.Columns.Add("resourcename3", typeof(string));
- dt.Columns.Add("resourcename4", typeof(string));
- dt.Columns.Add("resourcename5", typeof(string));
- dt.Columns.Add("fitsex1", typeof(int));
- dt.Columns.Add("fitsex2", typeof(int));
- dt.Columns.Add("fitsex3", typeof(int));
- dt.Columns.Add("fitsex4", typeof(int));
- dt.Columns.Add("fitsex5", typeof(int));
- for (int i = 0; i < 5000; i++)
- {
- DataRow row = dt.NewRow();
- row[0] = "王虎" + i.ToString();
- row[1] = "王虎" + i.ToString();
- row[2] = "王虎" + i.ToString();
- row[3] = "王虎" + i.ToString();
- row[4] = "王虎" + i.ToString();
- row[5] = i;
- row[6] = i;
- row[7] = i;
- row[8] = i;
- row[9] = i;
- dt.Rows.Add(row);
- }
- ds.Tables.Add(dt);
- var watch = new Stopwatch();
- watch.Start();
- var ModelList = ds.ToList<Model_Resource>(0);
- watch.Stop();
- ViewData["Message"] = string.Format("ModelList.count={0},Elapsed Milliseconds:{1}", ModelList.Count.ToString(),watch.ElapsedMilliseconds.ToString());
- return View();
- }
我使用的類定義如下:
- /// <summary>
- /// 實體類Resource 。(屬性說明自動提取數據庫字段的描述信息)
- /// </summary>
- [Serializable]
- public class Model_Resource
- {
- public Model_Resource()
- { }
- #region Model
- /// <summary>
- /// 資源標準名稱
- /// </summary>
- public string ResourceName1
- {
- get;
- set;
- }
- /// <summary>
- /// 資源標準名稱
- /// </summary>
- public string ResourceName2
- {
- get;
- set;
- }
- /// <summary>
- /// 資源標準名稱
- /// </summary>
- public string ResourceName3
- {
- get;
- set;
- }
- /// <summary>
- /// 資源標準名稱
- /// </summary>
- public string ResourceName4
- {
- get;
- set;
- }
- /// <summary>
- /// 資源標準名稱
- /// </summary>
- public string ResourceName5
- {
- get;
- set;
- }
- /// <summary>
- /// 適合的性別 1 男 2 女 3 均可
- /// </summary>
- public string FitSex1
- {
- get;
- set;
- }
- /// <summary>
- /// 適合的性別 1 男 2 女 3 均可
- /// </summary>
- public string FitSex2
- {
- get;
- set;
- }
- /// <summary>
- /// 適合的性別 1 男 2 女 3 均可
- /// </summary>
- public string FitSex3
- {
- get;
- set;
- }
- /// <summary>
- /// 適合的性別 1 男 2 女 3 均可
- /// </summary>
- public string FitSex4
- {
- get;
- set;
- }
- /// <summary>
- /// 適合的性別 1 男 2 女 3 均可
- /// </summary>
- public string FitSex5
- {
- get;
- set;
- }
- #endregion Model
- }
看一下測試結果:
注:
性能上還可以通過緩存等機制優化一下,不過這方面已經有一些大牛做過了,以后有時間可以加進去。
原文鏈接:http://www.cnblogs.com/wbpmrck/archive/2011/04/12/2013730.html
【編輯推薦】