Linq从列表中选择

时间:2014-10-08 13:54:08

标签: asp.net-mvc vb.net linq

我似乎无法弄清楚这一点,我对MVC模型并不陌生,但也许我的大脑已经累了。

查看模型

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

当我运行此操作时,我在Category = From x....

上收到“无效的强制转换异常”
Unable to cast object of type 'WhereSelectListIterator`2[Library.cihCategoryOrgDef,Library.cihCategoryOrgDef]' to type 'Library.cihCategoryOrgDef'.

我正在尝试在我的视图中使用单个Category。所以我可以有一个特定类别的编辑页面。我是不是错了?

2 个答案:

答案 0 :(得分:1)

由于Category类别,因此您需要确保LINQ返回单个结果。如果您确定查询只返回一个值,请使用SingleOrDefault

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

如果您的查询可能返回多个结果而您只想获取第一个结果,请使用FirstOrDefault

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

答案 1 :(得分:1)

您的选择实际上会返回一个集合,这就是您获得无效投射异常的原因。要只获得一个项目,你需要这样的东西(抱歉,我对vb不是很熟悉,所以这里是c#代码):

Category = (From x In Categories
               Where x.codId = codId
               Select x).DefaultIfEmpty(null).FirstOrDefault();