for循环用于字符串变量

时间:2010-02-23 18:22:34

标签: vb.net string for-loop

这是我的代码 -

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 =”&在行(i)( “名称”) ... 等等。 有没有办法制作一个for循环并一次性运行申请人1,2,3,4 .... 感谢

3 个答案:

答案 0 :(得分:6)

尝试:

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 :(得分:0)

你真的不能尝试追加50个不同的领域。 您唯一可以缩短的是变量名称:

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

然后你简单地把它们放在一起

output &= strLN & strFirstName...etc

答案 2 :(得分:0)

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

    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