Retrieve values from a List - vb.net

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)

Related

String Manipulation from "[1_5],[1_3],[1_5]" to "5,3,5"

I have the a string in below format
Dim str as String = "[1_5],[1_3],[1_5]"
The part before the _ can be variable is not a fix number
i need to convert it in to format
"5,3,5"
i have used the below code to obtain all the number that i need in the new string in the matches Item Groups
Dim pattern As String = "_(.*?)\]"
Dim matches As MatchCollection =
Regex.Matches(rowpanel.getRequestedArea_selectionArea(), pattern, RegexOptions.Singleline)
My question is how i can join all the Groups to obtain the final string format ?
A Regex solution could be
Dim x = matches.Select(Function(g) g.Groups(1).Value)
Dim final = String.Join(",", x)
A Split and Join one is
Dim blocks As String() = str.Split(",")
Dim result = New List(Of String)()
For Each s In blocks
result.Add(s.Split("_")(1).Trim("]"))
Next
Dim final = String.Join(",", result)
You can do something like this using RegEx and replace:
Dim str As String = "[1_5],[1_3],[1_5]"
Dim RegX As Regex = New Regex("\[\d{1}_")
Dim match As Match = RegX.Match(str)
If match.Success Then
str = Replace(str, match.Value, "")
str = Replace(str, "]", "")
End If
Alternative with simple and readable loop but multiple lines of code wrapped with a method
Public Function ExtractNumbers(text As String) As String
Dim current As New StringBuilder()
Dim write As Boolean = False
For Each character As Char In text
If character = "_"c Then
write = True
Continue For
End If
If character = "]"c Then
write = False
current.Append(",")
Continue For
End If
If write Then
current.Append(character)
Continue For
End If
Next
current.Length -= 1
Return current.ToString()
End Function
Usage
var extracted = ExtractNumbers("[1_5],[1_3],[1_5]")
Console.WriteLine(extracted)
' 5,3,5

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

Split String into Textboxes

I have this URL:
http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>
How to get parts of this into Textboxes?
ie:
Textbox1 = number after ?age=
Textbox2 = number after &Team=
Textbox3 = number after &userID=
If you want to output to a TextBox and can guarantee a set amount of parameters this is quite simple:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
TextBox1.Text = url.Split("?"c)(1).Split("&"c)(0).Split("="c)(1)
TextBox2.Text = url.Split("?"c)(1).Split("&"c)(1).Split("="c)(1)
TextBox3.Text = url.Split("?"c)(1).Split("&"c)(2).Split("="c)(1)
The code looks a little unreadable but it does the job. Note the increase in number on the second Split. This is the output:
Now what I would do is further checking to ensure the parameters are there and that they have values:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
Dim parameters As String = Nothing
If url.Contains("?") Then
parameters = url.Split("?"c)(1)
End If
Dim age As Integer = 0
Dim team As Integer = 0
Dim userId As Integer = 0
If parameters IsNot Nothing Then
For Each parameter In parameters.Split("&"c)
If parameter.Contains("=") Then
If parameter.ToLower().StartsWith("age") Then
Integer.TryParse(parameter.Split("="c)(1), age)
ElseIf parameter.ToLower().StartsWith("team") Then
Integer.TryParse(parameter.Split("="c)(1), team)
ElseIf parameter.ToLower().StartsWith("userid") Then
Integer.TryParse(parameter.Split("="c)(1), userId)
End If
End If
Next
End If
TextBox1.Text = age.ToString()
TextBox2.Text = team.ToString()
TextBox3.Text = userId.ToString()
The output is the same as above but I have done further checking. I'm sure even more checking could be put in place but I think this will give you a good start.
What I like to do is store both the name and the value of the parameter using a Dictionary which can come in handy so thought I would show you this approach:
Dim url As String = "http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>"
Dim urlParameters As New Dictionary(Of String, String)
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Dim kp() As String = param.Split("="c)
urlParameters.Add(kp(0), kp(1))
Next
End If
'ouput
For Each parameter In urlParameters
Debug.WriteLine("Key: " & parameter.Key & " Value:" & parameter.Value)
Next
This is a screenshot of the output:
If you only want to look at the value of the parameter and output that then you could simply do this instead of adding to a Dictionary:
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Debug.WriteLine(param.Split("="c)(1))
Next
End If
In this case the output will be:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=100&userID=1109"
Dim temp As String = url.Substring(url.IndexOf("?")+1)
Dim args() As String
args = temp.Split("&")
Dim pair() As String
For Each arg As String In args
pair = arg.Split("=")
console.WriteLine(pair(0))
console.WriteLine(pair(1)) ' <--- value after =
Next

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

How can iterate in Dictionary in vb.net?

I create a dictionary
Dim ImageCollection As New Dictionary(Of ConvensionImages, Integer)
and I fill that
For Each dr As DataRow In dt.Rows
Dim obj As New ConvensionImages
obj.ImageID = dr("ID")
obj.Name = dr("Name")
obj.Description = dr("Description")
obj.CategoryID = dr("CategoryID")
obj.CategoryName = dr("CategoryName")
obj.CategoryDescription = dr("CatDescription")
obj.EventID = dr("EventID")
obj.Image = dr("img")
obj.DownloadImage = dr("DownLoadImg")
ImageCollection.Add(obj, key)
key = key + 1
now I want to search ImageID and key how can I do this
Make Integer as key for your Dictionary:
Dim ImageCollection As New Dictionary(Of Integer, ConvensionImages)
Change ImageCollection.Add(obj, key) to ImageCollection.Add(key, obj)
And use this loop:
For Each kvp As KeyValuePair(Of Integer, ConvensionImages) In ImageCollection
Dim v1 As Integer = kvp.Key
Dim v2 As ConvensionImages = kvp.Value
'Do whatever you want with v2:
'If v2.ImageID = .... Then
Next
You can loop this way, too:
For Each iKey As Integer In ImageCollection.Keys
Dim value As ConvensionImages = ImageCollection(iKey)
'...
Next
It is very fast and simple way to it.