none
Convert string to list and retrieve value based on text RRS feed

  • Question

  • Hi, I have a simple question.

    we have a Visual basic program where we store few variables in database.

    instead of making muliple calls to database we retrieve  a single value from database which is them splitted and retrieved as required.

    Value is stored and retrived from database as a string which will be like Value1="XX"#value2="yy"#value3="ZZ"#value4=""AA"

    I can convert this to a list using split like below

    Dim arr() As String = value1.Split("#")

    Now we have the list like

    • Value1="XX"
    • Value2="yy"value3="ZZ"
    • value4=""AA"

    now how can i retrieve value's based up on the requirement. ?

    Eg: from the above called list if i need to retrieve the value of Value2 how this can be done ?

    variable 1 = "yy" (retreived by searching for  value2 in the retrieved text.

    Thanks in advance.


    Coderv9

    Sunday, August 5, 2018 6:06 PM

Answers

  • You can use a TextFieldParser to split the string on both the # and = characters.  It will also handle the values being wrapped in quotes.

    You can then loop through the resulting array of strings, two at a time, to build a dictionary of key-value pairs.  Finally you can access items from that dictionary.

    This example will do the above process and would also handle multiple lines of strings in case you want to make more than one query and combine the results with a CRLF character before splitting into key-value pairs.

    Public Function GetKeyValues(source As String) As Dictionary(Of String, String)
        Dim result As New Dictionary(Of String, String)
        Using reader As New IO.StringReader(source)
            Using tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser(reader)
                tfp.SetDelimiters("#", "=")
                tfp.HasFieldsEnclosedInQuotes = True
                While Not tfp.EndOfData
                    Dim values = tfp.ReadFields
                    For i = 0 To values.Length - 1 Step 2
                        result(values(i)) = values(i + 1)
                    Next
                End While
            End Using
        End Using
        Return result
    End Function
    

    Here some example usage:

    Dim dbstring As String = "Value1=""XX""#value2=""yy""#value3=""ZZ""#value4=""AA"""
    Dim values = GetKeyValues(dbstring)
    
    'get one result
    Label1.Text = values("value2")
    
    'enumerate all results
    For Each key In values.Keys
        RichTextBox1.AppendText($"{key} = {values(key)}")
        RichTextBox1.AppendText(vbCrLf)
    Next
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, August 5, 2018 6:21 PM
    Moderator

All replies

  • You can use a TextFieldParser to split the string on both the # and = characters.  It will also handle the values being wrapped in quotes.

    You can then loop through the resulting array of strings, two at a time, to build a dictionary of key-value pairs.  Finally you can access items from that dictionary.

    This example will do the above process and would also handle multiple lines of strings in case you want to make more than one query and combine the results with a CRLF character before splitting into key-value pairs.

    Public Function GetKeyValues(source As String) As Dictionary(Of String, String)
        Dim result As New Dictionary(Of String, String)
        Using reader As New IO.StringReader(source)
            Using tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser(reader)
                tfp.SetDelimiters("#", "=")
                tfp.HasFieldsEnclosedInQuotes = True
                While Not tfp.EndOfData
                    Dim values = tfp.ReadFields
                    For i = 0 To values.Length - 1 Step 2
                        result(values(i)) = values(i + 1)
                    Next
                End While
            End Using
        End Using
        Return result
    End Function
    

    Here some example usage:

    Dim dbstring As String = "Value1=""XX""#value2=""yy""#value3=""ZZ""#value4=""AA"""
    Dim values = GetKeyValues(dbstring)
    
    'get one result
    Label1.Text = values("value2")
    
    'enumerate all results
    For Each key In values.Keys
        RichTextBox1.AppendText($"{key} = {values(key)}")
        RichTextBox1.AppendText(vbCrLf)
    Next
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, August 5, 2018 6:21 PM
    Moderator
  • Dim SIndex As Integer = Array.FindIndex(arrVal, (Function(c As String) c.StartsWith("value2"))) If SIndex <> -1 Then

    MsgBox(Strings.Mid(arrVal(SIndex), Strings.InStr(arrVal(SIndex), "=") + 1))

    Else

    MsgBox("Search string not found!", MsgBoxStyle.Information, "Search Array")

    End If



    Shishir

    Sunday, August 5, 2018 6:45 PM
  • Hi

    You can also try regular expressions.

            Dim s As List(Of String) = Regex.Matches(TextBox1.Text, """[^""]*""").Cast(Of Match)().[Select](Function(x) x.Groups(0).Value).ToList
    
            MsgBox(Regex.Replace(s(0), "[\""]+", ""))

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, August 6, 2018 6:32 AM
  • You are awesome Reed . Code works perfectly for our requirement.  

    Coderv9

    Tuesday, August 7, 2018 11:30 AM
  • You are awesome Reed . Code works perfectly for our requirement.  

    Coderv9

    You're welcome.

    One caveat to keep in mind is that the keys in the dictionary (value1, value2, value3, etc.) must be unique.  I'm guessing that since those are column names in a table, this isn't an issue, but it is worth noting that should you have a string with multiple key-value pairs with the same key, it will cause the last pair added to be the only one in the dictionary.  I can only see this being an issue if you were to combine multiple query results into a single string and two tables happened to have the same column name.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


    Tuesday, August 7, 2018 11:43 AM
    Moderator