Cory House
Cory House

Reputation: 15045

Converting LINQ to XML result to generic list in VB.NET. Odd error

I have a function that works great in C# that I'm converting to VB.NET. I'm having an issue converting the result set to a generic list in VB.NET.

The code:

    Public Function GetCategories() As List(Of Category)
        Dim xmlDoc As XDocument = XDocument.Load("http://my_xml_api_url.com")
        Dim categories = (From category In xmlDoc.Descendants("Table") _
        Select New Category()).ToList(Of Category)()

        Return categories
    End Function

The error occurs when converting the result via .ToList(Of Category)(). The error:

Public Function ToList() As System.Collections.Generic.List(Of TSource)' defined in 'System.Linq.Enumerable' is not generic (or has no free type parameters) and so cannot have type arguments.

Category is a simple object I've created, stored in the App_Code directory.

I have the necessary "Imports System.Collections.Generic" reference in the file, so I don't see why I can't convert the result set to a generic list.

Upvotes: 2

Views: 2798

Answers (2)

Heinzi
Heinzi

Reputation: 172390

The answer is simple: Replace ToList(Of Category)() with ToList().

As a side note: Maybe you want New Category(category) instead of New Category()? At the moment, your code is creating a list of empty categories...

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502376

It's saying that because you're invoking it as an extension method on an IEnumerable<Category>, the type argument has already been specified. Just get rid of the type argument:

Dim categories = (From category In xmlDoc.Descendants("Table") _
                  Select New Category()).ToList()

That's equivalent to writing:

Dim categories = Enumerable.ToList(Of Category) _
    (From category In xmlDoc.Descendants("Table") _
     Select New Category())

Upvotes: 5

Related Questions