将DataTable 存到一个集合当中
生活随笔
收集整理的這篇文章主要介紹了
将DataTable 存到一个集合当中
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
將DataTable 存到一個(gè)集合中
此做法來自: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;
????????}
????}
}
?
?
?
以上代碼有兩個(gè)方法,一個(gè)是獲取一個(gè)DataTable的方法,這個(gè)我們可以自己用ADO.NET獲取,這里要說的是第二個(gè)方法,第二個(gè)方法的思想是:
將每一行存儲(chǔ)到一個(gè)鍵值對(duì)集合中,當(dāng)前行的每列用一個(gè)key-value對(duì)存儲(chǔ),最后將這些鍵值對(duì)集合存到List集合中,這樣就得到了一個(gè)List<Dictionary<string,object>> 類型的集合了。
?
當(dāng)我們將DataTable集合轉(zhuǎn)換成集合之后就可以很方便的將其傳到前臺(tái)頁(yè)面、或者View視圖了。
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/key1309/p/3460847.html
總結(jié)
以上是生活随笔為你收集整理的将DataTable 存到一个集合当中的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于TCP和多线程实现无线鼠标键盘-Ge
- 下一篇: UTC Time