【问题标题】:asp.net splitting xml DataTableasp.net拆分xml数据表
【发布时间】:2013-10-08 16:02:09
【问题描述】:

我有一个从 xml 文件中填充的数据集,我想将该主数据表拆分为多个数据表。

假设这是表格的格式:

Column1 | Column2
1234    | 4567
1234    | 1122
1234    | 2233
1000    | 3344
1000    | 5566

我需要将以上内容分成 2 个表,一个包含所有 1234 个值,一个包含 1000 个值。

这就是我读取 xml 文件的方式并且可以正常工作:

WebClient wc = new WebClient();
            wc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            string strXmlString = wc.DownloadString(strUrl); // Download the URL to a string
            strXmlString = Regex.Replace(strXmlString, @"m:null.+?>{1}", @"/>"); // Find ' m:null[anything]>' and replace it with '/>'
            strXmlString = Regex.Replace(strXmlString, @"[\s]{1}m:.+?>{1}", @">"); // Find ' m:type[anything]>' and replace it with '>'
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(strXmlString); // Load the XML String into an XML Doc
            XmlReader xReader = new XmlNodeReader(xDoc);
            DataSet ds = new DataSet();
            ds.ReadXml(xReader); // Upload the XML Doc Data to the DataSet

如何将ds.Tables[0] 拆分为 2 个表?

【问题讨论】:

    标签: c# asp.net datatable dataset


    【解决方案1】:
    DataTable dt1  = ds.Tables[0].Select("Column1 ='1000'").CopyToDataTable();
    DataTable dt2 = ds.Tables[0].Select("Column1 ='1234'").CopyToDataTable();
    

    【讨论】:

      【解决方案2】:

      你可以使用 Linq,尤其是Enumerable.GroupBy:

      var column1Groups = ds.Tables[0].AsEnumerable()
          .GroupBy(r => r.Field<string>("Column1"));
      foreach(var group in column1Groups)
      {
          // if you need only the 1234  and 1000 groups:
          if(group.Key == "1000" || group.Key == "1234")
          {
              ds.Tables.Add(group.CopyToDataTable());
          }
      }
      

      与几乎纯 Linq 相同:

      var valuesNeeded = new[]{ "1000", "1234" };
      var newTables = ds.Tables[0].AsEnumerable()
          .GroupBy(r => r.Field<string>("Column1"))
          .Where(g => valuesNeeded.Contains(g.Key))
          .Select(g => g.CopyToDataTable())
          .ToArray();
      ds.Tables.Clear(); // if you need to clear it first
      ds.Tables.AddRange( newTables );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多