Or you could write a class that takes the string as an input and spits out a name value collection:
- Imports System.Collections.Specialized
-
Public Class NameValueCollectionEx
-
Inherits NameValueCollection
-
Private _RecordDelimiter As String = "&"
-
Private _FieldDelimiter As String = "="
-
Public Property FieldDelimiter() As String
-
Get
-
Return _FieldDelimiter
-
End Get
-
Set(ByVal value As String)
-
_FieldDelimiter = value
-
End Set
-
End Property
-
Public Property RecordDelimiter() As String
-
Get
-
Return _RecordDelimiter
-
End Get
-
Set(ByVal value As String)
-
_RecordDelimiter = value
-
End Set
-
End Property
-
Public Property DataString() As String
-
Get
-
Dim sOut As String = Nothing
-
For Each sItem As String In MyBase.AllKeys
-
sOut &= sItem & _FieldDelimiter & MyBase.Item(sItem) & _RecordDelimiter
-
Next
-
sOut = sOut.Substring(0, sOut.Length - 1)
-
Return sOut
-
End Get
-
Set(ByVal value As String)
-
Dim sData() As String = Split(value, _RecordDelimiter)
-
For Each sItem As String In sData
-
MyBase.Add(Split(sItem, _FieldDelimiter)(0), Split(sItem, _FieldDelimiter)(1))
-
Next
-
End Set
-
End Property
-
Public Sub New()
-
End Sub
-
Public Sub New(ByVal NameValueString As String)
-
DataString = NameValueString
-
End Sub
-
Public Sub New(ByVal NameValueString As String, ByVal RecordDelimiter As String, ByVal FieldDelimiter As String)
-
_RecordDelimiter = RecordDelimiter
-
_FieldDelimiter = FieldDelimiter
-
DataString = NameValueString
-
End Sub
-
End Class
-
Module Module1
-
Sub Main()
-
Dim InputStr As String = "FirstName=Ben&MiddleName=&LastName=Alabaster&EmpId=259486"
-
Dim NVC As New NameValueCollectionEx(InputStr)
-
For Each Item As String In NVC.AllKeys
-
Console.WriteLine(Item & ": " & NVC(Item))
-
Next
-
Console.ReadLine()
-
End Sub
-
End Module
As you can see from the Main() method, you can now just reference the name value collection:
Dim MyCol As New NameValueCollectionEx(InputStr)
You would reference the items as:
MyCol("name")
MyCol("code")
MyCol("dept")
etc...
That class allows you to specify delimiters other than & and =. The field delimiter splits the record into key and value and the record delimiter splits the records. The defaults are & and = though.