我是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 。
答案 0 :(得分: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
答案 1 :(得分: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