将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< stringobject>> GetTableRows(DataTable dtData)
        {
            List<Dictionary< stringobject>> lstRows =  new List<Dictionary< stringobject>>();
            Dictionary< stringobject> dictRow =  null;

             foreach (DataRow dr  in dtData.Rows)
            {
                dictRow =  new Dictionary< stringobject>();
                 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值