Jeremiah Jeschke
Jeremiah Jeschke

Reputation: 107

Pairs from a list of string in vb.net

I'm trying to pair elements of a list of string together, ie, out of a list of a,b,c,d; I'd like to see ab, bc, cd. Here's the code I have so far:

    Dim C As New List(Of String)
    For i = 0 To S.Count - 1
        For j =i + 1 To S.Count - 1
            C.Add("{" & S(i) & "," & S(j) & "}")
        Next
    Next
    Dim value As String = String.Join(",", C)
    TextBox2.Text = value

Currently, this code returns a power set of {a,b},{a,c},{a,d},{b,c},{b,d},{c,d}..

Is there an efficient way to do this?

Upvotes: 0

Views: 1187

Answers (2)

Fabian Bigler
Fabian Bigler

Reputation: 10895

As simple as that:

Dim input As String = "a,b,c,d"
Dim output As String = String.Empty
Dim toggleIgnoreComma As Boolean = True

For Each s As String In input
    If s.Equals(","c) Then
        If toggleIgnoreComma Then
            toggleIgnoreComma = False
            Continue For
        Else
            toggleIgnoreComma = True
        End If
    End If

    output += s
Next

Upvotes: 0

J Collins
J Collins

Reputation: 2170

It looks like you only want adjacent pairs so this should work for you:

Dim C As New List(Of String)
For i = 0 To S.Count - 2
    C.Add("{" & S(i) & "," & S(i + 1) & "}")
Next
Dim value As String = String.Join(",", C)
TextBox2.Text = value

If so, simpler still:

Dim C As New List(Of String)
For i = 0 To S.Count - 2
    C.Add(String.Format("{{{0},{1}}}", {S(i), S(i + 1)}))
Next
TextBox2.Text = String.Join(",", C)

Upvotes: 1

Related Questions