在Visual Basic中连接数组的元素

时间:2015-10-19 22:34:29

标签: arrays vb.net string concatenation

嘿,我遇到了一个令人不安的问题,基本上我有一个数组Dim array() as String = {"Team1, "Team2", "Team3", "Team4", "Team5" }

我的目标是使用字符串" vs"连接偶数对中的字符串。 AND 如果有奇数个对将数组中的奇数元素连接到字符串" Bye" 所以我试图让我的输出看起来像这样Team1 vs Team2, Team3 vs Team4, Team5 vs Bye

我知道我需要使用循环但是我很困惑如何将原始数组中未知数量的元素变成偶数对2,以便我可以连接字符串!任何帮助将非常感激!

3 个答案:

答案 0 :(得分:1)

我会避免循环并使用LINQ。这就是我要做的事情:

Dim array As String() = { "Team1", "Team2", "Team3", "Team4", "Team5" }

Dim working = array
If working.Length Mod 2 = 1 Then
    working = working.Concat({ "Bye" }).ToArray()
End If

Dim output = _
    working.Where(Function (x, n) n Mod 2 = 0) _
        .Zip(working.Where(Function (x, n) n Mod 2 = 1), _
            Function (x1, x2) String.Format("{0} vs {1}", x1, x2)) _
    .ToArray()

这给出了:

output

使用LINQ执行此操作的另一种方法是:

Dim output = _
    working _
        .Select(Function (x, n) New With { .Team = x, .Group = n \ 2 }) _
        .GroupBy(Function (x) x.Group, Function (x) x.Team) _
        .Select(Function (xs) String.Join(" vs ", xs)) _
        .ToArray()

有8支球队:

Team1 vs Team2 
Team3 vs Team4 
Team5 vs Team6 
Team7 vs Team8 

有3支球队:

Team1 vs Team2 
Team3 vs Bye 

拥有10,001支球队:

Team1 vs Team2 
Team3 vs Team4 
Team5 vs Team6 
...
Team9997 vs Team9998 
Team9999 vs Team10000 
Team10001 vs Bye 

如果你需要它作为字符串而不是数组,那么就这样做:

Dim text = String.Join(", ", output)

这给你这样的事情:

  

Team1 vs Team2,Team3 vs Team4,Team5 vs Team6,Team7 vs Team8,Team9 vs Team10,Team11 vs Team12,Team13 vs Team14,Team15 vs Team16,Team17 vs Bye

答案 1 :(得分:0)

您可以通过添加Step参数将For循环增加2。但是不是循环到Count - 1,而是应该循环到其中的一半。这在一定程度上取决于球队数量的奇数/均匀度。连接时,使用loop参数和参数加1来访问数组元素。例如:

dim game as string = teams(i) & teams(i + 1)

答案 2 :(得分:0)

你可以创建一个for循环并使用2的步骤。使用StringBuilder来组装最终的字符串。

Dim array() as String = { "Team1", "Team2", "Team3", "Team4", "Team5" }
Dim sb As New StringBuilder() 
For i = 0 To array.Length - 1 Step 2
    Dim s1 As String = array(i) 
    Dim s2 As String = If(i + 1 < array.Length, array(i + 1), "Bye")
    sb.Append(s1).Append(" vs ").Append(s2).Append(", ")
Next
If sb.Length > = 2 Then
    sb.Length -= 2
End If
Dim result = sb.ToString() ' ==> "Team1 vs Team2, Team3 vs Team4, Team5 vs Bye"