sd_dracula
sd_dracula

Reputation: 3896

asp.net splitting xml DataTable

I have a DataSet which gets populated from an xml file and I would like to split that main DataTable into several DataTables.

Let's say this is the format of the table:

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

I need to split the above into 2 tables, one that contains all the 1234 values and one for the 1000 values.

This is how I read the xml file and that work correctly:

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

How would I split the ds.Tables[0] into 2 tables?

Upvotes: 0

Views: 453

Answers (2)

Damith
Damith

Reputation: 63065

DataTable dt1  = ds.Tables[0].Select("Column1 ='1000'").CopyToDataTable();
DataTable dt2 = ds.Tables[0].Select("Column1 ='1234'").CopyToDataTable();

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use Linq and especiall 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());
    }
}

The same with nearly pure 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 );

Upvotes: 1

Related Questions