将DataTable 存到一个集合当中
生活随笔
收集整理的這篇文章主要介紹了
将DataTable 存到一个集合当中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將DataTable 存到一個集合中
此做法來自:http://www.codeproject.com/Articles/692832/Simple-way-of-using-SQL-DataTables-to-JSON-in-MVC
?
?
using?System;using?System.Data;
using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
namespace?MvcApplication31.ViewModels
{
????public?class?DataAccessLayer
????{
????????public?DataTable?GetTable()
????????{
????????????DataTable?dtTable?=?new?DataTable();
????????????dtTable.Columns.Add("UserID",?typeof(int));
????????????dtTable.Columns.Add("FirstName",?typeof(string));
????????????dtTable.Columns.Add("LastName",?typeof(string));
????????????dtTable.Rows.Add(25,?"Ave",?"Maria");
????????????dtTable.Rows.Add(50,?"Bill",?"Doe");
????????????dtTable.Rows.Add(75,?"John",?"Gates");
????????????dtTable.Rows.Add(99,?"Julia",?"Griffith");
????????????dtTable.Rows.Add(100,?"Mylie",?"Spears");
????????????return?dtTable;
????????}
????????public?List<Dictionary<string,?object>>?GetTableRows(DataTable?dtData)
????????{
????????????List<Dictionary<string,?object>>?lstRows?=?new?List<Dictionary<string,?object>>();
????????????Dictionary<string,?object>?dictRow?=?null;
????????????foreach?(DataRow?dr?in?dtData.Rows)
????????????{
????????????????dictRow?=?new?Dictionary<string,?object>();
????????????????foreach?(DataColumn?col?in?dtData.Columns)
????????????????{
????????????????????dictRow.Add(col.ColumnName,?dr[col]);
????????????????}
????????????????lstRows.Add(dictRow);
????????????}
????????????return?lstRows;
????????}
????}
}
?
?
?
以上代碼有兩個方法,一個是獲取一個DataTable的方法,這個我們可以自己用ADO.NET獲取,這里要說的是第二個方法,第二個方法的思想是:
將每一行存儲到一個鍵值對集合中,當前行的每列用一個key-value對存儲,最后將這些鍵值對集合存到List集合中,這樣就得到了一個List<Dictionary<string,object>> 類型的集合了。
?
當我們將DataTable集合轉換成集合之后就可以很方便的將其傳到前臺頁面、或者View視圖了。
?
?
轉載于:https://www.cnblogs.com/key1309/p/3460847.html
總結
以上是生活随笔為你收集整理的将DataTable 存到一个集合当中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于TCP和多线程实现无线鼠标键盘-Ge
- 下一篇: UTC Time