Add two string arrays to dictionary - vb.net

I want to merge two string arrays in a Dictionary
I tried this:
Dim array1() As String = {"A","B"}
Dim array2() As String = {"a","b"}
Dim Dict As Dictionary(Of String, String)
For i = 0 To array1.Count() - 1
Dict.Add(array1(i), array2(i))
Next
but i got Null

Dim array1() As String = {"A","B"}
Dim array2() As String = {"a","b"}
Dim Dict As New Dictionary(Of String, String)
For i = 0 To array1.Count() - 1
Dict.Add(array1(i), array2(i))
Next
You don't New the Dictionary, i.e. no object to work with.

Related

Sort str strwords in VB.Net

Can i make little short that code? I would not like to write this too many times, so I would like to make it shorter. just for the first 5, i don't want for all the lines of the textbox.
str2 = TxtBoxIntDraws1.Lines(0)
Dim strWords2 As String() = str2.Split(",")
str3 = TxtBoxIntDraws1.Lines(1)
Dim strWords3 As String() = str3.Split(",")
str4 = TxtBoxIntDraws1.Lines(2)
Dim strWords4 As String() = str4.Split(",")
str5 = TxtBoxIntDraws1.Lines(3)
Dim strWords5 As String() = str5.Split(",")
str6 = TxtBoxIntDraws1.Lines(4)
Dim strWords6 As String() = str6.Split(",")
You can do like following
For idx = 0 To 4
str = TxtBoxIntDraws1.Lines(idx)
Dim strWords As String() = str.Split(",")
Next idx
If you want to process the split words later you can save the data to an array and process later.
Follow the following code for this.
Dim idx As Integer
Dim strWords(5)() As String
For idx = 0 To 4
str = TxtBoxIntDraws1.Lines(idx)
strWords(idx) = str.Split(",")
Next idx
' process strWords
Paraphrase of the answer by Vignesh Kumar A. This will give you lines 1 - 4. The index starts at zero.
Private Sub OPCode()
Dim blankList As New List(Of String())
For i = 0 To 3
blankList.Add(TextBox1.Lines(i).Split(","c))
Next
End Sub

from list to string with formatting

i have a function getSelectedNumbers that take as input 3 list of number. after a manipulation i need to obtain a string in the format
"[1_3,10,20,30,500],[1_1,2],[]"
if the list is empty i need to have in the string the "[]" char
i wrote the below function but i need to manage the empty case.
Based on comment of Anu6is :
i was able to rewrite my code as below
'''vb
Public Function getSelectedNumbers() As String
Dim selectedNumbers1 As IList(Of Element) = repo.CanvasTerminalProduct.BoardDetails.Panel.pnlSuper3Panel1.Find(".//div[#class='selected']")
Dim selectedNumbers2 As IList(Of Element) = repo.CanvasTerminalProduct.BoardDetails.Panel.pnlSuper3Panel2.Find(".//div[#class='selected']")
Dim selectedNumbers3 As IList(Of Element) = repo.CanvasTerminalProduct.BoardDetails.Panel.pnlSuper3Panel3.Find(".//div[#class='selected']")
Dim list1 As New List(Of String)
Dim list2 As New List(Of String)
Dim list3 As New List(Of String)
For i As Integer = 0 To selectedNumbers1.Count -1
list1.Add(selectedNumbers1(i).GetAttributeValue("innerText").ToString)
Next i
For i As Integer = 0 To selectedNumbers2.Count -1
list2.Add(selectedNumbers2(i).GetAttributeValue("innerText").ToString)
Next i
For i As Integer = 0 To selectedNumbers3.Count -1
list3.Add(selectedNumbers3(i).GetAttributeValue("innerText").ToString)
Next i
'Create List of List
Dim selectedNumbersList As New List(Of List(Of String)) From {list1, list2, list3}
Dim builder As New StringBuilder 'Used to build the output
'Convert all the list in the correct string format using the join
For Each listX As List(Of String) In selectedNumbersList
builder.Append("[1_").Append(String.Join(",", listX)).Append("],") 'String.Join() give you a comma delmited string
Next
'Remove the last, and the [1_] that are not needed
Dim strSelectedNunmber As String = builder.ToString().TrimEnd(","c)
strSelectedNunmber = strSelectedNunmber.ToString().Replace("[1_]","[]")
Return str
End Function
'''
now my question is there is a better way to generate the list1 list2 list3 ?
This is assuming that Element is simply an Integer
Public Function getSelectedNumbers() As String
Dim selectedNumbers1 As New List(Of Integer) From {20, 30, 500, 10, 3} 'Unordered list
Dim selectedNumbers2 As New List(Of Integer) From {1, 2, 500} 'Ordered list
Dim selectedNumbers3 As New List(Of Integer) 'empty list
Dim selectedNumbersList As New List(Of List(Of Integer)) From {selectedNumbers1, selectedNumbers2, selectedNumbers3}
Dim builder As New StringBuilder 'Used to build the output
For Each list In selectedNumbersList
list.Sort() 'Sort your list
builder.Append("[").Append(String.Join(",", list)).Append("],") 'String.Join() give you a comma delmited string
Next
Return builder.ToString.TrimEnd(","c) 'Remove the final comma (,) and return the formatted string
End Function
[3,10,20,30,500],[1,2,500],[]
Does this work for you?
Dim selectedNumbers1 As New List(Of Integer) From {20, 30, 500, 10, 3}
Dim selectedNumbers2 As New List(Of Integer) From {1, 2, 500}
Dim selectedNumbers3 As New List(Of Integer)
'either make 3 loops or 1, but you have to make a list of lists first
Dim selectedNumbersList As New List(Of List(Of Integer)) From {selectedNumbers1, selectedNumbers2, selectedNumbers3}
For Each listX In selectedNumbersList
listX.Sort()
Dim ReturnString As String = "["
If listX.Count > 0 Then
For Each itemvalue In listX
ReturnString &= itemvalue & ","
Next
ReturnString = ReturnString.Remove(ReturnString.Length - 1)
End If
ReturnString &= "]"
Debug.Print(ReturnString)
Next
'[3,10,20,30,500]
'[1,2,500]
'[]

Retrieve values from a List

I want to store 100 items in a list with properties PartName and PartId.
I then want to search on PartName, as an example using the word chair. From this I then want to retrieve the value of PartId.
In the end I will end up with a PartId of 125.
How can I do this?
Code:
Dim parts As New List(Of Intialization)()
' Add parts to the list.
parts.Add(New Intialization() With {.PartName = "chair",
.PartId = 125})
You could achieve this in several ways, I´ll show you some LINQ solutions:
Dim partToSearch as String = "Chair"
Dim partId as Integer = -1
Dim init = parts.Where(Function(p) p.PartName=partToSearch).FirstOrDefault()
If init IsNot Nothing Then
partId = init.PartId
End If
Or:
Dim partToSearch as String = "Chair"
Dim partId = parts.Where(Function(p) p.PartName=partToSearch).Select(Function(v) v.PartId).FirstOrDefault()
Or you create a Dictionary like #the_lotus mentioned:
Dim partIDsByName as Dictionary(Of String, Integer)
partIDsByName = parts.ToDictionary(Function(k) k.PartName, Function(v) v.PartId)
Dim partToSearch as String = "Chair"
Dim partId = partIDsByName(partToSearch)

Converting String to Structure

I am successfully converted structure data to string here in plain and (as suggested) in XML serialized way which obviously every has it's own good and bad side effects.
This is sample structure:
Public Structure myList
Dim a As String
Dim b As Integer
Dim c As Double
End Structure
Dim myInstance As New myList
myInstance.a = "Nemo"
myInstance.b = 10
myInstance.c = 3.14
Now I have 2 functions for converting structure data to string:
Dim xString As String = oStructToString(myInstance)
Public Function oStructToString(ByVal obj As Object) As String
Dim structString As String = ""
Dim i As Integer
Dim myType As Type = obj.GetType()
Dim myField As System.Reflection.FieldInfo() = myType.GetFields()
For i = 0 To myField.Length - 1
structString &= myField(i).GetValue(obj)
If i = myField.Length - 1 Then Exit For
structString &= Convert.ToChar(161)
Next i
Return structString
End Function
Dim xString As String = xStructToString(myInstance)
Public Function xStructToString(ByVal obj As Object) As String
Dim x As New Xml.Serialization.XmlSerializer(obj.GetType)
Dim sw As New IO.StringWriter()
x.Serialize(sw, obj)
Return sw.ToString
End Function
But I can't get data back from string to structure.
Public Function oStringToStruct(ByVal xString As String) As Object
So I can call:
Dim mySecondInstance As New myList = oStringToStruct(xString)
Or
Dim mySecondInstance As New myList = xStringToStruct(xString)
How to do that?
So far I came to this:
Public Function xStringToStruct(ByVal xString As String) As Object
Dim x As New Xml.Serialization.XmlSerializer() ''<- what here?
Dim sr As New IO.StringReader(xString)
Return x.Deserialize(sr)
End Function
and this...
By help of har07 still one error remains here...
Public Function oStringToStruct(ByVal xString As String, ByVal type As Type) As Object
Dim structString() As String = xString.Split(Convert.ToChar(161))
Dim myType As Type = type.GetType()
Dim myField As System.Reflection.FieldInfo() = myType.GetFields()
For i As Integer = 0 To structString.Length - 1
myField(i).SetValue(type, structString(i)) ''here crashes
Next i
Return type
End Function
Deserialize xml string back to struct is easier :
Public Function xStringToStruct(ByVal xString As String, ByVal type As Type) As Object
Dim x As New Xml.Serialization.XmlSerializer(type)
Dim sw As New IO.StringReader(xString)
Return x.Deserialize(sw)
End Function
You can use it like so :
Dim xObject As myList = xStringToStruct(xString, GetType(myList))

Building a multidimensional array in vb.net

I'm trying to build up a multidimensional array which will hold two bits of info for each record in a database e.g. id, description.
This is what I am currently doing.
Dim mArray(,) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
End While
The problem I have here is that it doesn't like the i in mArray(i,0). Anyone have any ideas about this? This is the error that is given Object reference not set to an instance of an object.
Thanks for any and all help.
Nalum
Why not rather make use of List Class and Dictionary Class
You can rather then create a List of Dictionaries, with the key and value both strings. The key can then represent your key (id and description in your example, and the value can be what ever was stored).
Something like
Dim values As New List(Of Dictionary(Of String, String))()
and then in the while loop something like
values.Add(New Dictionary(Of String, String)() From { _
{"id", cmdReader.Item("id")} _
})
values.Add(New Dictionary(Of String, String)() From { _
{"description", cmdReader.Item("description")} _
})
You could then use foreach
For Each value As Dictionary(Of String, String) In values
Dim id As String = value("id")
Dim description As String = value("description")
Next
Or a for
For i As Integer = 0 To values.Count - 1
Dim value As Dictionary(Of String, String) = values(i)
Dim id As String = value("id")
Dim description As String = value("description")
Next
Try this
Dim mArray(1,1) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
ReDim Preserve mArray(i,1)
End While
The problem is that you are not initializing the array.
This should work, until i will not reach the limits set in the initialization.
Dim mArray(100,100) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
End While
But if the array limits are not known I suggest to follow astander's suggestion.
This works for me:
Dim values As New List(Of Dictionary(Of String, String))()
values.Add(New Dictionary(Of String, String)() From {{"quarter", q1.ToString}, {"year", y1.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q2.ToString}, {"year", y2.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q3.ToString}, {"year", y3.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q4.ToString}, {"year", y4.ToString}})
For Each value As Dictionary(Of String, String) In values
Dim quarter As String = value("quarter")
Dim year As String = value("year")
Debug.Print(quarter & "/" & year)
Next
Correct it by
Dim mArray(,) As String = ""