zoukankan      html  css  js  c++  java
  • DataTable的用法

    在项目中经常用到DataTable,如果DataTable使用得当,不仅能使程序简洁实用,而且能够提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结。

    一、DataTable简介    

              (1)构造函数 
              DataTable()   不带参数初始化DataTable 类的新实例。 
              DataTable(string tableName)  用指定的表名初始化DataTable 类的新实例。 
              DataTable(string tableName, string tableNamespace) 用指定的表名和命名空间初始化DataTable 类的新实例。 
              (2) 常用属性 
              CaseSensitive    指示表中的字符串比较是否区分大小写。 
              ChildRelations   获取此DataTable 的子关系的集合。 
              Columns             获取属于该表的列的集合。 
              Constraints        获取由该表维护的约束的集合。 
              DataSet               获取此表所属的DataSet。 
              DefaultView       获取可能包括筛选视图或游标位置的表的自定义视图。 
              HasErrors          获取一个值,该值指示该表所属的DataSet 的任何表的任何行中是否有错误。 
              MinimumCapacity  获取或设置该表最初的起始大小。该表中行的最初起始大小。默认值为 50。 
              Rows                  获取属于该表的行的集合。 
              TableName       获取或设置DataTable 的名称。 

              (3)常用方法 
              AcceptChanges()   提交自上次调用AcceptChanges() 以来对该表进行的所有更改。 
              BeginInit()         开始初始化在窗体上使用或由另一个组件使用的DataTable。初始化发生在运行时。

              Clear()               清除所有数据的DataTable。 
              Clone()              克隆DataTable 的结构,包括所有DataTable 架构和约束。 
              EndInit()            结束在窗体上使用或由另一个组件使用的DataTable 的初始化。初始化发生在运行时。 
              ImportRow(DataRow row)    将DataRow 复制到DataTable 中,保留任何属性设置以及初始值和当前值。 
              Merge(DataTable table)  将指定的DataTable 与当前的DataTable 合并。 
              NewRow()         创建与该表具有相同架构的新DataRow。
     
    二、DataTable使用技巧

    1)Create a DataTable
             DataTable dt = new DataTable("Table_AX"); 
    
          (2)Add columns for DataTable
            //Method 1
            dt.Columns.Add("column0", System.Type.GetType("System.String"));
            //Method 2
            DataColumn dc = new DataColumn("column1", System.Type.GetType("System.Boolean"));
            dt.Columns.Add(dc); 
    
           (3)Add rows for DataTable
             //Initialize the row
             DataRow dr = dt.NewRow();
             dr["column0"] = "AX";
             dr["column1"] = true;
             dt.Rows.Add(dr);
             //Doesn't initialize the row
             DataRow dr1 = dt.NewRow();
             dt.Rows.Add(dr1);  
    
            (4)Select row
             //Search the second row 如果没有赋值,则用is null来select
             DataRow[] drs = dt.Select("column1 is null");
             DataRow[] drss = dt.Select("column0 = 'AX'"); 
    
            (5)Copy DataTable include data
             DataTable dtNew = dt.Copy(); 
    
            (6)Copy DataTable only scheme
             DataTable dtOnlyScheme = dt.Clone(); 
    
            (7)Operate one row
             //对dt的操作
             //Method 1
             DataRow drOperate = dt.Rows[0];
             drOperate["column0"] = "AXzhz";
             drOperate["column1"] = false;
             //Method 2
             drOperate[0] = "AXzhz";
             drOperate[1] = false;
             //Method 3
             dt.Rows[0]["column0"] = "AXzhz";
             dt.Rows[0]["column1"] = false;
             //Method 4
             dt.Rows[0][0] = "AXzhz";
             dt.Rows[0][1] = false; 
    
           (8)Evaluate another DataTable's row to current Datatable
             dtOnlyScheme.Rows.Add(dt.Rows[0].ItemArray); 
    
           (9)Convert to string
             System.IO.StringWriter sw = new System.IO.StringWriter();
             System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
             dt.WriteXml(xw);
             string s = sw.ToString();
    
            (10)Filter DataTable
             dt.DefaultView.RowFilter = "column1 <> true";
             dt.DefaultView.RowFilter = "column1 = true";
    
            (11)Sort row
              dt.DefaultView.Sort = "ID ,Name ASC";
              dt=dt.DefaultView.ToTable();
    
             (12)Bind DataTable
               //绑定的其实是DefaultView
              gvTestDataTable.DataSource = dt;
              gvTestDataTable.DataBind();
    
             (13)judge the DataTable’s Column name is a string
              //判断一个字符串是否为DataTable的列名
             dtInfo.Columns.Contains("AX");
    
             (14)DataTable convert to XML and XML convert to DataTable
              protected void Page_Load(object sender, EventArgs e)
              {
                 DataTable dt_AX = new DataTable();
                 //dt_AX.Columns.Add("Sex", typeof(System.Boolean));
                 //DataRow dr = dt_AX.NewRow();
                 //dr["Sex"] = true;
                 //dt_AX.Rows.Add(dr);
                 string xml=ConvertBetweenDataTableAndXML_AX(dt_AX);
                 DataTable dt = ConvertBetweenDataTableAndXML_AX(xml);
             }
             public string ConvertBetweenDataTableAndXML_AX(DataTable dtNeedCoveret)
            {
                 System.IO.TextWriter tw = new System.IO.StringWriter();
                 //if TableName is empty, WriteXml() will throw Exception.                 
    
    dtNeedCoveret.TableName=dtNeedCoveret.TableName.Length==0?"Table_AX":dtNeedCoveret.TableName;
                 dtNeedCoveret.WriteXml(tw);
                 dtNeedCoveret.WriteXmlSchema(tw);
                 return tw.ToString();
            }
             public DataTable ConvertBetweenDataTableAndXML_AX(string xml)
            {
                 System.IO.TextReader trDataTable = new System.IO.StringReader(xml.Substring(0, xml.IndexOf("<?xml")));
                 System.IO.TextReader trSchema = new System.IO.StringReader(xml.Substring(xml.IndexOf("<?xml")));
                 DataTable dtReturn = new DataTable();
                 dtReturn.ReadXmlSchema(trSchema);
                 dtReturn.ReadXml(trDataTable);
                 return dtReturn;
            }

    例:

    第一个:

    DataTable dt = new DataTable();
                dt.Columns.Add("ID",typeof(int));
                dt.Columns.Add("Name",typeof(string));
                dt.Columns.Add("Sex",typeof(string));
                DataRow dr = dt.NewRow();
                dr["ID"] = "1";
                dr["Name"] = "张三";
                dr["Sex"] = "";
                dt.Rows.Add(dr);
                 dr = dt.NewRow();
                dr["ID"] = "2";
                dr["Name"] = "李四";
                dr["Sex"] = "";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["ID"] = "12";
                dr["Name"] = "旺旺";
                dr["Sex"] = "";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["ID"] = "22";
                dr["Name"] = "王五";
                dr["Sex"] = "";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["ID"] = "32";
                dr["Name"] = "赵六";
                dr["Sex"] = "";
                dt.Rows.Add(dr);

    第二个:按照其中已知的某一列排序(根据实际列的类型需要修改代码)

    static  public DataTable DtSortA(DataTable Dt, string column)
            {
                DataTable dtNew = Dt.Clone();
                dtNew.Columns[column].DataType = typeof(DateTime);
                foreach (DataRow s in Dt.Rows)
                {
                    dtNew.ImportRow(s);//导入旧数据
                }
                dtNew.DefaultView.Sort = column + " desc";
                dtNew = dtNew.DefaultView.ToTable();
                return dtNew;
            }
          static public DataTable DtSortB(DataTable Dt, string column)
            {
                DataTable dtNew = Dt.Clone();
                foreach (DataRow item in Dt.AsEnumerable().OrderByDescending(a => Convert.ToDateTime(a[column])))
                {
                    dtNew.ImportRow(item);
                }
                return dtNew;
            }
    DataTable dt_order_soon = dt_invest.Clone();//克隆表
    
                if (dt_invest != null && dt_invest.Rows.Count > 0)
                {
                    DataRow[] dt_soon = dt_invest.Select("1=1");//筛选条件
                    for (int e = 0; e < dt_soon.Length; e++)
                    {
                        var day = new JBLProCompute.InComeCount().ReturnDays(DateTime.Now, Convert.ToDateTime(dt_soon[e]["DateOver"].ToString()));
                        if (day >= 0 && day <= 7)
                        {
                            dt_order_soon.ImportRow(dt_soon[e]);
                        }
                    }
               }
    DataTable dt = new DataTable();
                dt.Columns.Add("ID", typeof(int));//Type.GetType("System.String")
                dt.Columns.Add("Name",typeof(string));
                dt.Columns.Add("Sex",typeof(string));
                DataRow dr = dt.NewRow();
                dr["ID"] = "1";
                dr["Name"] = "张三";
                dr["Sex"] = "";
                dt.Rows.Add(dr);
                DataTable ddt = new DataTable();
                //输出指定的列数据
               ddt= dt.DefaultView.ToTable(false,new string[] {"ID","Name"});

    第三个:

    DataTable dt = new DataTable();
                dt.Columns.Add("ID", typeof(int));//Type.GetType("System.String")
                dt.Columns.Add("Name",typeof(string));
                dt.Columns.Add("Sex",typeof(string));
                DataRow dr = dt.NewRow();
                dr["ID"] = "1";
                dr["Name"] = "张三";
                dr["Sex"] = "";
                dt.Rows.Add(dr);////想要输出xml格式,当前的Datatable表必须要有表名
               dt.TableName = "myData";//添加Datatable表名才能输出xml格式
               System.IO.StringWriter dsw = new System.IO.StringWriter();
               System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(dsw);
               dt.WriteXml(xw);
               string s = dsw.ToString();
                //将xml格式转成Datatable格式,直接是xml格式的字符串最外层是根节点,第二层是表名,三层是字段和数据
               string strxml = @"<xml><Login><ID>1</ID><Name>小明</Name></Login><Login><ID>2</ID><Name>小万</Name></Login></xml>";
    
              //第二种是文件读入xml
              XmlDocument docddd=new XmlDocument();
              docddd.Load(Server.MapPath("/datatable.xml")); 
              DataTable dt_xml = ConvertXMLToDataSet(docddd.InnerXml).Tables[0];
  • 相关阅读:
    Building a RESTful Web Service
    Proxy setting
    同步机制 note
    C++: Virtual Table and Shared Memory
    2018中国大学生程序设计竞赛
    2018 MUltiU 9 dp / 8 upper_bound ; 构造?/
    2018/8/10 部分枚举(类似尺取)
    2018/8/9 MultiU 6 并查集+dfs,反向建边提高查询效率 !!! / 最大字段和n维(降维)/ 状压+中途相遇法
    2018/7/29 cf 499 div 2(1011)
    2018/7/28 欧拉路径
  • 原文地址:https://www.cnblogs.com/jiangshuai52511/p/7272415.html
Copyright © 2011-2022 走看看