zoukankan      html  css  js  c++  java
  • 将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视图了。

  • 相关阅读:
    动态规划 简单的分割问题的解决方案钢棒
    SICP 1.20经验
    辛星一起了解下后续PHP性能功能
    汽车之家购买价格PC真正的原因阿拉丁
    可怜,的分母。
    [ACM] poj 1064 Cable master (二进制搜索)
    从Access创建Sqlite数据库
    变化的阅读程序猿自学习
    ArcEngine载入中SDE问题栅格数据
    pinyin4j新手教程
  • 原文地址:https://www.cnblogs.com/key1309/p/3460847.html
Copyright © 2011-2022 走看看