VB.NET LINQ Group By Into Select New无法访问类成员BC30456



我正在尝试将以下教程中的一些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"子句,否则";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})

您需要声明谁将成为您的密钥。根据您的代码,应该是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#正在计算它必须是"0";流派":

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
}

最新更新