将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;
}
}
}
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视图了。