You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中如何获取List集合具体值?已实现实现GridView绑定需遍历取值

问题描述

我有一个GetTags方法,绑定到GridView时可正常工作,代码如下:

GridView1.DataSource = Me.GetTags

完整的方法及类定义:

Partial Class backoffice_posts_Edit
    Private Function GetTags() As List(Of Tag)
        Dim constring As String = ConfigurationManager.ConnectionStrings("AccessConnectionString1").ConnectionString
        Using con As New SqlConnection(constring)
            Using cmd As New SqlCommand("SELECT tag_id FROM tags_tbl WHERE tag_choice = 1", con)
                Dim tags As New List(Of Tag)
                cmd.CommandType = CommandType.Text
                con.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        tags.Add(New Tag With {
                                      .tagId = Convert.ToInt32(sdr("tag_id"))
                                    })
                    End While
                End Using
                con.Close()
                Return tags
            End Using
        End Using
    End Function
End Class

Public Class Tag
    Public Property tagId As Integer
End Class

但我不想使用GridView,需要遍历该List集合的取值(后续要根据条件判断,比如判断tag值是否为23等)。我编写了以下代码,但输出的是tag;tag;tag;tag;tag;tag;而非实际数值:

For Each element In Me.GetTags
    Response.Write(element)
    Response.Write(";")
Next

请问如何获取List中每个Tag对象的tagId实际值?

解决方案

直接输出element时,实际是打印Tag类的实例本身,默认情况下对象的ToString()方法会返回类名,所以才会输出重复的tag;。要获取实际的tagId值,直接访问对象的tagId属性即可:

修改遍历代码为:

For Each element In Me.GetTags
    Response.Write(element.tagId)
    Response.Write(";")
Next

如果需要做条件判断(比如判断tagId是否为23),可以在循环中添加逻辑:

For Each element In Me.GetTags
    If element.tagId = 23 Then
        ' 执行你的处理逻辑
        Response.Write("找到目标tagId: 23;")
    Else
        Response.Write(element.tagId & ";")
    End If
Next

内容的提问来源于stack exchange,提问作者compliance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:39:25