如何使用LINQ ASP.NET从两个DataTable创建一个新的DataTable

时间:2012-05-22 13:13:40

标签: asp.net vb.net linq join datatable

再次是我:D

我正在学习LINQ,我想做的事情是我无法做到的。请不要建议其他不是Linq的解决方案。感谢。

    Dim dtSong As DataTable = New DataTable("Songs")
    dtSong.Columns.Add("ID", GetType(Guid))
    dtSong.Columns.Add("Name", GetType(String))
    dtSong.Columns.Add("Type", GetType(String))
    dtSong.Columns.Add("AlbumID", GetType(Guid))

    Dim dtAlbum As DataTable = New DataTable("Album")
    dtAlbum.Columns.Add("ID", GetType(Guid))
    dtAlbum.Columns.Add("Name", GetType(String))

    Dim idsong, idalbum As Guid
    idalbum = Guid.NewGuid()
    dtAlbum.Rows.Add(idalbum, "Best of")

    idsong = Guid.NewGuid()
    dtSong.Rows.Add(idsong, "You are my sunshine", "Pop", idalbum)
    idsong = Guid.NewGuid()
    dtSong.Rows.Add(idsong, "twinkle twinkle", "Pop", idalbum)
    idsong = Guid.NewGuid()
    dtSong.Rows.Add(idsong, "you are my heart", "Rock", idalbum)        


    Dim query = From x In dtSong Join y In dtAlbum
                On x.Field(Of Guid)("AlbumID") Equals
                y.Field(Of Guid)("ID")
                Where (x.Field(Of String)("Type") = "Pop")
                Select New With
                     {
                        .Name = x.Field(Of String)("Name"),
                        .Type = x.Field(Of String)("Type"),
                        .Album = y.Field(Of String)("Name")
                    }

    Dim dtnew As DataTable = query.CopyToDataTable

我猜我的LINQ查询有问题。我不允许在此查询中使用CopyToDataTable。我可以使用For Each循环打印出结果,但我希望有一个新的DataTable。谢谢您的帮助。抱歉英语很差。

0 个答案:

没有答案