0

我有一个这样的数据表

  X,Y,Z
  0,0,A
  0,2,B
  0,0,C
  1,0,A
  1,0,C
  2,2,A
  2,2,B
  2,0,C
  3,2,B
  3,1,C
  4,3,A
  4,0,B
  4,1,C
  5,3,A
  5,2,B
  5,0,C

我想把它转换成这样的东西:

  X,A,B,C
  0,0,2,0
  1,0, ,0
  2,2,2,0
  3, ,2,1
  4,3,0,1
  5,3,2,0

我尝试使用数据集和 linq,但我并不幸运。

我的 linq 代码:

    Dim q = (From c In dt _
          Select c("Z") Distinct) 'I found out which categories I have in Z column (my example :A,B,C)
     Dim ldt(q.Count) As DataTable

     For i = 0 To q.Count - 1
        Dim sfil As String = q(i).ToString
        Dim r = (From c In dt _
        Select c Where c("Z") = sfil)
        ldt(i) = r.CopyToDataTable
     Next

所以现在我有 3 个表(ldt(0) 的值为 A,ldt(1) 的值为 B,ldt(2) 的值为 C),我正在考虑做类似 leftJoin 的事情,但我尝试过的任何事情都失败了. 有什么解决方案甚至更好的主意吗?

谢谢

所以一个新的例子是:我有这个表:

 id,Price,Item
  0,0,Laptop
  0,2,Tablet
  0,0,Cellphone
  1,0,Laptop
  1,0,Tablet
  2,2,Laptop
  2,2,Cellphone
  2,0,Tablet
  3,2,Cellphone
  3,1,Tablet
  4,3,Laptop
  4,0,Cellphone
  4,1,Tablet
  5,3,Laptop
  5,2,Cellphone
  5,0,Tablet

我想将其转换为:

  X,Laptop,Tablet,Cellphone
  0,0,2,0
  1,0, ,0
  2,2,2,0
  3, ,2,1
  4,3,0,1
  5,3,2,0

笔记本电脑、平板电脑、手机每列的值是第一个表中的 Y 值。

我希望它现在更有意义。

4

1 回答 1

0

我相信您可以使用与项目名称对应的列名称创建一个 DataTable。然后,您对先前的 DataTable 进行id分组,并使用每个分组来填充一行。如果我做错了什么,请原谅我。我不太会使用 VB 或 DataTables。

Dim itemNames = (From c In dt _
                 Select c("Item") Distinct)

Dim newDt as DataTable = new DataTable()
Dim idColumn As DataColumn = new DataColumn()
idColumn.DataType = System.Type.GetType("System.Int32")
idColumn.ColumnName = "id"
idColumn.ReadOnly = True
idColumn.Unique = True 

newDt.Columns.Add(idColumn)

For Each itemName As String In itemNames
    Dim column As DataColumn = new DataColumn()
    column.DataType = GetType(Nullable(Of Integer))
    column.ColumnName = itemName
    column.ReadOnly = True
    column.Unique = False
    newDt.Columns.Add(column)
Next

Dim groupingById = From row in dt
                   Group By Id = row("id")
                   Into RowsForId = Group

For Each grouping In groupingById
    Dim row as DataRow = newDt.NewRow()
    row("id") = grouping.Id
    For Each rowForId in grouping.RowsForId
        row(rowForId("Item")) = rowForId("Price")
    Next
    newDt.Rows.Add(row)
Next
于 2012-09-19T19:37:04.190 回答