A3006
A3006

Reputation: 1069

LINQ result in DataRow

I have an XML for which I have used LINQ to XML. As I wanted to capture some of the element/ attribute data, I have taken them in a string array. Later I have used a foreach loop to insert these values from string array to a DataRow; as my final goal is to get a DataTable out of it.

Following is my code

System.Data.DataTable dt = new System.Data.DataTable();

    dt.Columns.Add("col_1");
    dt.Columns.Add("col_2");
    dt.Columns.Add("col_3");
    string[] arr = new string[3];

    var myData = from n in doc.Descendants("product")
             select new string[]{ 
                 arr[0] = n.Attribute("name").Value,
                 arr[1] = n.Attribute("prodid").Value,
                 arr[2] = n.Attribute("price").Value
             };

    foreach (var item in myData)
    {
        dt.Rows.Add(item[0],item[1],item[2]);
    }

Is is possible to combine these and directly get an output as DataTable from LINQ query instead of using foreach?

Instead of select new string[] can I use something like select new DataTable or instance of DataTable?

I understand that my Table structure should be fixed.

Update

Thanks @CodingDawg & @Rahul Singh, I would now like to know the best approach between these two.

I will check for my sample data to compare the same.

But from your experience which one is better considering large data (10000 elements => 10000 rows)?

Upvotes: 2

Views: 2346

Answers (2)

Praveen Reddy
Praveen Reddy

Reputation: 7383

Use the Linq .ToList().ForEach() functions

System.Data.DataTable dt = new System.Data.DataTable();

dt.Columns.Add("col_1");
dt.Columns.Add("col_2");
dt.Columns.Add("col_3");

 doc.Descendants("product")
            .ToList()
            .ForEach(
                n => dt.Rows.Add(n.Attribute("name").Value,
                                 n.Attribute("prodid").Value, 
                                 n.Attribute("price").Value));

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 21795

There is way to load entire XML into DataSet but I guess you need some specific values and also need to do some custom filtering or stuffs thus you are using Linq-to-XML, you can project the datatable directly without using foreach loop like this:-

DataTable myData = doc.Descendants("product")
                      .Select(x => 
                         {
                            var row = dt.NewRow();
                            row.SetField<string>("col_1", (string)x.Attribute("name"));
                            row.SetField<string>("col_2", (string)x.Attribute("prodid"));
                            row.SetField<string>("col_1", (string)x.Attribute("price")); 
                            return row;
                         }).CopyToDataTable();

myData will hold the resultant dataTable.

Upvotes: 4

Related Questions