【问题标题】:How to Loop through LINQ results (VB.NET)如何循环遍历 LINQ 结果 (VB.NET)
【发布时间】:2010-05-17 23:30:42
【问题描述】:

我有一些代码可以尝试遍历 LINQ 结果,但它似乎不起作用。

这是代码

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        ''# the page contenttype is plain text'
        HttpContext.Current.Response.ContentType = "text/plain"

        ''# store the querystring as a variable'
        Dim qs As Nullable(Of Integer) = Integer.TryParse(HttpContext.Current.Request.QueryString("ID"), Nothing)

        ''# use the RegionsDataContext'
        Using RegionDC As New DAL.RegionsDataContext

            ''# create a (q)uery variable'
            Dim q As Object

            ''# if the querystring PID is not blank'
            ''# then we want to return results based on  the PID'
            If Not qs Is Nothing Then
                ''# that fit within the Parent ID'
                q = (From r In RegionDC.bt_Regions _
                        Where r.PID = qs _
                       Select r.Region).ToArray

                ''# now we loop through the array'
                ''# and write out the ressults'
                For Each item As DAL.bt_Region In q
                    HttpContext.Current.Response.Write(item.Region & vbCrLf)
                Next

            End If



        End Using
    End Sub

这是错误

类型上的公共成员“区域” 未找到“字符串”。说明:一个 期间发生未处理的异常 当前网络的执行 要求。请查看堆栈跟踪 有关错误的更多信息 以及它起源于代码的位置。

异常详情: System.MissingMemberException:公共 'String' 类型的成员 'Region' 不是 找到了。

来源错误:

第 33 行:' 和 写出结果第 34 行:
对于 q 第 35 行中的每个项目:
HttpContext.Current.Response.Write(item.Region & vbCrLf) 第 36 行:
下第 37 行:

源文件: E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb 线路:35

堆栈跟踪:

[MissingMemberException:公共成员 未找到类型“字符串”的“区域”。] Microsoft.VisualBasic.CompilerServices.Container.GetMembers(字符串& MemberName,布尔型报告错误) +509081 Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(对象 实例,类型,字符串 成员名称,对象 [] 参数, 字符串 [] 参数名称,类型 [] TypeArguments, Boolean[] CopyBack) +222 BT.Handlers.RegionsAutoComplete.ProcessRequest(HttpContext 上下文)在 E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb:35 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean & completedSynchronously) +75

谁能告诉我我做错了什么?

【问题讨论】:

    标签: vb.net linq foreach


    【解决方案1】:

    错误消息表明存储在 bt_Regions 属性中的对象属于 String 类型,因此它们没有您尝试访问的成员 Region

    我会仔细检查 DAL.bt_Regions 的类型 - 看起来你假设它返回了某个类,但它似乎返回了一个字符串集合(可能只是区域名称?)。要查看它包含的内容,您可以像这样修改代码:

    HttpContext.Current.Response.Write(item & vbCrLf) // to print the string 
    

    我还会尝试添加Option Strict On 选项(如果可能),它会指示编译器在编译时检查此类错误。

    【讨论】:

    • 啊是的。使用“项目”有效,因为我只从数据库中选择一条记录(这是一个字符串)。
    猜你喜欢
    • 2019-11-30
    • 2013-09-14
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2015-10-05
    相关资源
    最近更新 更多