我有一个包含这些列表字符串的数组:
a -- b -- c
d -- e -- f
g -- h -- i
我想得到这个:
(a,b,c),(d,e,f),(g,h,i)
这是我的代码:
'I iterate through the entire list to create the string
Dim valueChain As String = ""
Dim lista As New List(Of String)
For Each item In MyArrayList
For Each subitem In item
valueChain += subitem.ToString + " ,"
Next
' I remove the last ,
valueChain = valueChain.TrimEnd(",")
valueChain = "(" + valueChain + ") ,"
Next
lista.Add(valueChain)
但我明白了:
(((a,b,c),d,e,f),g,h,i),
我怎么能得到这个? :
(a,b,c),(d,e,f),(g,h,i)
答案 0 :(得分:2)
您只需添加一次价值链。而是尝试在第一个循环中添加它并在此之后清除valueChain。
Dim lista As New List(Of String)
For Each item In MyArrayList
Dim valueChain As String = ""
For Each subitem In item
valueChain += subitem.ToString + ","
Next
valueChain = valueChain.TrimEnd(",")
valueChain = "(" + valueChain + ")"
lista.Add(valueChain)
Next
您将在lista
中获得3件物品。
答案 1 :(得分:1)
首先,我建议您使用&符号(&
)并置运算符而不是加号(+
),因为&符号专门用于此目的。
现在你的代码。如果你想让它像你写的一样紧凑,你应该在添加子项时删除空格:
valueChain &= subitem.ToString & ","
请注意,如果这已经是ToString
的数组,则不需要String
。
然后,在每个主阵列的迭代中,你会在链之前添加一个括号(
。您应该在开始迭代子项之前附加括号,然后在之后附加右括号:
For Each item In MyArrayList
'Append the opening bracket.
valueChain &= "("
For Each subitem In item
valueChain &= subitem.ToString & ","
Next
'Remove the last comma
valueChain = valueChain.TrimEnd(",")
'Append the closing bracket and the comma.
valueChain &= "), "
Next
'Remove the last comma and space.
valueChain = valueChain.TrimEnd(", ")
lista.Add(valueChain)
希望这有帮助!
答案 2 :(得分:0)
我添加了这个:
Dim lista As New List(Of String)
For Each item In MyArrayList
Dim valueChain As String = ""
For Each subitem In item
valueChain += subitem.ToString + ","
Next
valueChain = valueChain.TrimEnd(",")
valueChain = "(" + valueChain + ")"
lista.Add(valueChain)
Next
然后添加此项以创建字符串:
Dim char As String = ""
For i As Integer = 0 To lista.Count - 1
char+= lista(i) + " ,"
Next
'I remove the last ,
char= char.TrimEnd(",")