Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27554

Is there more efficient method to do a DataTable Unpivot?

$
0
0
Hello,

I have two datatables that look like this.

Code:

        Dim dt As New DataTable
        dt.Columns.Add("COL1")
        dt.Columns.Add("COL2")
        dt.Columns.Add("COL3")
        dt.Columns.Add("COL4")
        dt.Columns.Add("COL5")

        Dim dt2 As New DataTable
        dt2.Columns.Add("NAME")
        dt2.Columns.Add("VALUE")

I insert a datarow into the first table.

Code:

        Dim dr As DataRow = dt.NewRow()
        dr("COL1") = "Hello"
        dr("COL2") = "My"
        dr("COL3") = "Name"
        dr("COL4") = "Is"
        dr("COL5") = "Jlimited"
        dt.Rows.Add(dr)

Quote:

COL1 COL2 COL3 COL4 COL5
Hello My Name Is Jlimited
What I want to is unpivot the datatable into the second datatable.

Quote:

NAME VALUE
COL1 Hello
COL2 My
COL3 Name
COL4 Is
COL5 Jlimited
I have the following code that does what I want, but I have to loop through each datarow in the datatable and then through each data column within a given row.

Code:

        For Each r As DataRow In dt.Rows
            For Each c As DataColumn In r.Table.Columns
                Dim dr As DataRow = dt2.NewRow()
                dr("NAME") = c.ColumnName
                dr("VALUE") = r(c.ColumnName)
                dt2.Rows.Add(dr)
            Next
        Next

I am looking for a more efficient method to unpivot the datatable.
I have implemented the same process in T-SQL, but I want to avoid uploading my first datatable to a stored procedure, just to download the results to the second.

Been reading about LINQ a little bit and I think it is possible to do this using it, not sure of the syntax as LINQ is new to me. Any help would be appreciated.

Thanks
Jlimited

Viewing all articles
Browse latest Browse all 27554

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>