问题描述
我正在尝试从以下教程中将一些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",.Price = 23.95D})
books.Add(New Book With {.Author = "Douglas Coupland",.Title = "Generation X",.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})
解决方法
您需要声明谁将成为您的钥匙。根据您的代码,假设为Genre
。因此,您需要按照Morton的建议使用分组功能,或者必须为分组的List(of Book)
下面的代码显示了如何:
Dim booksGrouped = From b In books
Group b By Key = b.Genre Into g = Group
Select New Group(Of String,Book) With {.Key = Key,.Values = g}
For Each current In booksGrouped
For Each value In current.Values
With value
Console.WriteLine("Key:" & current.Key & "value: " & Strings.Join({ .Genre,.Author,.Price,.Title}," - "))
End With
Next
Next
,
您不需要明确说明密钥-C#代码指定了“ g.Key”,但是C#正在确定它必须为“流派”:
Dim booksGrouped = From b In books
Group b By b.Genre Into g = Group
Select New Group(Of String,Book) With {
.Key = Genre,.Values = g
}