0

我是 LINQ 的新手。我尝试了几种方法,但我无法得到我想要的结果。请帮助解决这个问题。VB.NET 中的 LINQ to SQL。

我正在使用 Ling to SQL 类来运行查询以获得预期的结果。在查询结果之后,我将使用它来填充 Datagridview 。我找不到以下问题的解决方案。有没有人可以帮忙?谢谢。

桌子:

bookID  authorID  authorname
111     101       Mark
222     102       Tim
333     103       John
444     104       Rebecca
111     102       Tim
111     103       John
222     104       Rebecca

结果应该是:

bookID   author1     author2         author3....

111      Mark            Tim                  John

222      TIm              Rebecca          N/A or Empty

333      John            N/A or Empty    N/A or Empty

444      Rebecca      N/A or Empty    N/A or Empty

我必须只使用LINQ

4

2 回答 2

0

您可以使用该GroupBy方法执行此操作

Dim results = db.Books.GroupBy(Function(b) b.bookID, Function(b) b.authorname)

或者,如果您更喜欢 linq 查询语法

Dim results = _
    From b In db.Books _
    Group b.authorname By bookID = b.bookID Into authorname = Group

您可以将其用作

For Each group In results
    Console.Write(group.Key)
    Console.Write(":")
    For Each name As String In group 
        Console.Write("  " & name)
    Next 
    Console.WriteLine()
Next 

输出

111: Mark Tim John
222: Tim Rebecca
333: John
444: Rebecca
于 2013-03-30T02:00:49.150 回答
0
Dim results = From b In db.Books Group b.authorname _ 
                By bookID = b.bookID Into nameg = Group select bookid,nameg

For each gr in results 
    Console.Write(gr.bookid)
    Console.Write(":")
    For Each name As String In gr.nameg 
    Console.Write("  " & name)
Next 
Console.WriteLine()
Next 
于 2013-03-30T14:58:05.633 回答