【问题标题】:for loop for a string variable用于字符串变量的 for 循环
【发布时间】:2010-02-23 18:22:33
【问题描述】:

这是我的代码 -

for i as integer = 0 to rows.count - 1
   output &= "Name =" & row(i)("Name")
   output &= "lastName =" & row(i)("lastName")
... 50 more fields
next

我需要这样的输出

Applicant1Name = MikeApplicant1lastName = ditkaApplicant2Name = TomApplicant2lastName = Brady ...

如何在不输入以下代码 50 次的情况下执行此操作 - 输出 &= "申请人" & i.tostring() + 1 &"Name = & row(i)("Name") ... 等等。 有没有办法制作一个 for 循环并一次性运行申请人 1,2,3,4....? 谢谢

【问题讨论】:

    标签: vb.net string for-loop


    【解决方案1】:

    试试:

    Dim output as New StringBuilder("")
    
    For i as Integer = 0 To rows.Count - 1
        output.append("Applicant" + i.ToString())
        Foreach(col as DataColumn in dt.Columns)  ' The datatable where your rows are
            Dim colName as string = col.ColumnName
            output.append(colName & "=" & rows(i)(colName).ToString())
        Next
        If i < rows.Count - 1 Then output.Append("|")
    Next
    

    StringBuilder 对于字符串连接更快,并且如果您将行保存在数据表中(我假设这正在发生,因为这就是您访问它们的方式),那么您只需遍历顶层的列名.

    【讨论】:

    • +1 以获得正确答案,如果可以提及使用 StringBuilder,我会给你 +2。很难夸大仅使用字符串连接大量文本的性能影响。
    • 行 - Foreach(col as DataColumn in dt.Columns),我在哪里声明 col?
    • @iregy - col 在该行中声明为 DataColumn。通过在 () 中执行此操作,您可以将其范围保持在直接块中。
    • 它给了我一个错误,说“名称'col'未声明”这是我制作的代码 - 使用 ds.Tables(2) For i As Integer = 0 To .Rows.Count - 1 output.Append("Applicant") For Each (col As DataColumn In ds.Tables(2)) output.Append("GivenName||" & .Rows(i)("firstname") & vbCrLf) output.Append(" LastName||" & .Rows(i)("lastname") & vbCrLf) Next If i
    • @iregy:鉴于您使用了“With”关键字,您需要在 for each 中以这种方式声明 col --> For Each (col as DataColumn In .Columns)
    【解决方案2】:

    你真的不能,因为你试图附加 50 个不同的字段。 唯一可以缩短的是变量名:

    Dim strLN as String = row(i)("lastName")
    Dim strFirstName as String = row(i)("firstName")
    

    然后你把它们放在一起

    output &= strLN & strFirstName...etc
    

    【讨论】:

    • “申请人”部分在哪里?我需要申请人 1 姓名、申请人 2 姓名等 50 个字段
    【解决方案3】:

    看起来您想创建一个包含所有字段的数组,然后包含一个嵌套循环。

        Dim fields As String() = {"Name", "LastName", "SSN", "Birthdate"}
        Dim output As String = ""
    
        For i As Integer = 1 To rows.count
            For Each field As String In fields
                output = String.Concat(output, "Applicant ", i, field, "=", row(i)(field), " ")
            Next
        Next
    

    【讨论】:

    • 那是不必要的。他可以遍历已经存在的列。在我看来,这比单独列出所有字段要好。
    • 不错,没想到。我大脑中存储有关 DataSets 和 DataTables 信息的部分因过度使用 ORM 而萎缩。
    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多