MaylorTaylor MaylorTaylor - 2 months ago 20
Vb.net Question

Linq select from list

I cant seem to figure this out, I'm not that new to the MVC model but perhaps my brain is just tired.

View Model

Public Class CategoriesViewModel
Public Property Categories As List(Of cihCategoryOrgDef)
Public Property Category As cihCategoryOrgDef
Public Property SelectedItem As String

Public Sub New(organizationId As Guid, codId As Guid)
Categories = lists.organizationClubCategories
Category = From x In Categories
Where x.codId = codId
Select x
End Sub
End Class


CategoriesController

Function Edit(codId As Guid) As ActionResult
Dim model As CategoriesViewModel = New CategoriesViewModel(ZenCommon.CurrentOrgId, codId)


Return View(model)
End Function


When I run this, I get a "invalid cast exception" on the
Category = From x....
line

Unable to cast object of type 'WhereSelectListIterator`2[Library.cihCategoryOrgDef,Library.cihCategoryOrgDef]' to type 'Library.cihCategoryOrgDef'.


I'm trying to get a single
Category
to use in my View. So I can have an edit page for that specific category. Am I going about this all wrong?

Answer

Since Category is a single category, you need to make sure your LINQ returns a single result. If you're sure that the query will only return one value, use SingleOrDefault:

Category = (From x In Categories
           Where x.codId = codId
           Select x).SingleOrDefault()

If your query could return more than one result and you only want to take the first result, use FirstOrDefault:

Category = (From x In Categories
           Where x.codId = codId
           Select x).FirstOrDefault()
Comments