MaylorTaylor MaylorTaylor - 1 year ago 126 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


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....

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

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

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download