【发布时间】:2020-08-13 21:50:33
【问题描述】:
我正在尝试将以下教程中的一些 C# 代码转换为 VB.NET,该教程展示了如何使用 LINQ Group By Into 生成带有行组标题的 HTML 表:
https://ole.michelsen.dk/blog/grouping-data-with-linq-and-mvc/
C# 代码可以像宣传的那样工作,但是我的 VB.NET 转换有问题。
我在 VB.NET 中遇到问题的工作 C# 代码行:
// Group the books by Genre
var booksGrouped = from b in books
group b by b.Genre into g
select new Group<string, Book> { Key = g.Key, Values = g };
Visual Studio 报告“g.Key”为:
string IGrouping<string, Book>.Key
在 VB.NET 中,Group 和 Book 这两个类如下所示:
Public Class Group(Of K, T)
Public Property Key As K
Public Property Values As IEnumerable(Of T)
End Class
Public Class Book
Public Title As String
Public Author As String
Public Genre As String
Public Price As Decimal
End Class
和上面的C#行代码一样为VB.NET:
Dim booksGrouped = From b In books Group b By b.Genre Into g = Group
Select New Group(Of String, Book) With {.Key = g.Key, .Values = g}
注意:我必须在 'Into' 子句中添加“= Group”,否则“g”会出现错误“BC36594:在此上下文中无法访问方法 'g' 的定义。”
Visual Studio 报告“g.Key”现在是一个 IEnumerable:
BC30456: 'Key' is not a member of 'IEnumerable(of Book)'.
所以 C# 看到的是 IGroup 接口,而 VB.NET 看到的是 IEnumerable。
我喜欢教程中提供的解决方案的简单性,并且真的很想在 VB.NET 中实现它,有人知道如何让它工作吗?
非常感谢。
VB.NET中的示例数据是
Dim books As New List(Of Book)
books.Add(New Book With {.Author = "Douglas Adams", .Title = "The Hitchhiker's Guide to the Galaxy", .Genre = "Fiction", .Price = 159.95D})
books.Add(New Book With {.Author = "Scott Adams", .Title = "The Dilbert Principle", .Genre = "Fiction", .Price = 23.95D})
books.Add(New Book With {.Author = "Douglas Coupland", .Title = "Generation X", .Genre = "Fiction", .Price = 300D})
books.Add(New Book With {.Author = "Walter Isaacson", .Title = "Steve Jobs", .Genre = "Biography", .Price = 219.25D})
books.Add(New Book With {.Author = "Michael Freeman", .Title = "The Photographer's Eye", .Genre = "Photography", .Price = 195.5D})
【问题讨论】:
-
关键字必须是标题、作者、流派或价格
-
Dim booksGrouped = books.GroupBy(Function(bk) bk.Genre).Select(Function(g) New Group(Of String, Book) With {.Key = g.Key, .Values = g})没有显示任何问题。 -
为了方便大家,我添加了示例数据的翻译。
-
替换了 Andrew 的代码,它现在可以工作了。谢谢。
标签: c# vb.net linq c#-to-vb.net