VB.net Dictionary loop - vb.net

Hey all i am in need of some help looping thru my Dictionary list. I can not seem to find the correct syntax in order to do so.
Here is my code:
Dim all = New Dictionary(Of String, Object)()
Dim info = New Dictionary(Of String, Object)()
Dim theShows As String = String.Empty
info!Logo = channel.SelectSingleNode(".//img").Attributes("src").Value
info!Channel = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(0).InnerText
info!Station = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(2).InnerText
info!Shows = From tag In channel.SelectNodes(".//a[#class='thickbox']")
Select New With {channel.Show = tag.Attributes("title").Value, channel.Link = tag.Attributes("href").Value}
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows") '<--Doesnt work...
I just want to extract whatever is in "Shows" from the all dictionary.

Your code,
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows")
The value of info!Station is being used as the KEY value in the all dictionary. Then you attempt to access the value using the constant string "Shows". I'm not sure what your intention was but
theShows = all.Item(info!Station)
should return the value of Shows that was stored using the Key info!Station.
If you want the list of shows as a string, you can do this,
Dim Shows as String = ""
For Each item in theShows
Shows &= item.Show & vbNewLine
Next

You can loop like this
For Each pair As KeyValuePair(Of String, String) In dict
MsgBox(pair.Key & " - " & pair.Value)
Next
source : VB.Net Dictionary
Winston

Related

Sum the repeated string list values and merge as one using linq in .net

The below code I tried to sum up the string value with the list values, it happens, but other values are not shown in return. I need to sum the values and other value should be returned to the object using linq in vb.net.
My code:
Dim lstrTaxValue As String = "YQ$40"
Dim lstaValues As New List(Of String)
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("PQ$8")
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("AQ$5")
Dim lobjTValues = (From lstr In lstaValues
From lval In lstrTaxValue.Split(" ")
Where (lstr.Split("$")(0) = CStr(lval).Split("$")(0))
Select (CStr(lval).Split("$")(0) & "$" & (CDbl(CStr(lval).Split("$")(1)) + CDbl(lstr.Split("$")(1))))).ToList()
What am I doing wrong?
To quote Jon Skeet...
Change some value inside the List<T>
In comments...
Why do you want to use lambda expressions? The foreach code works fine and is simple. LINQ is for querying data, not mutating it. – Jon Skeet
Your objective does not seem to lend itself to Linq.
Private Sub OPCode()
Dim lstrTaxValue As String = "YQ$40"
Dim lstaValues As New List(Of String)
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("PQ$8")
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("AQ$5")
Dim TaxValue = lstrTaxValue.Split("$"c)
For i = 0 To lstaValues.Count - 1
If lstaValues(i).Split("$"c)(0) = TaxValue(0) Then
lstaValues(i) = TaxValue(0) & "$" & CStr(CDbl(lstaValues(i).Split("$"c)(1)) + CDbl(TaxValue(1)))
End If
Next
For Each s In lstaValues
Debug.Print(s)
Next
End Sub
Result:
YQ$50
TQ$3
PQ$8
YQ$50
TQ$3
AQ$5

Decode mail encoded-words =?utf-8?B?xxxx?=, =?utf-8?Q?xxxx?=

Is there a way to decode email subjects that are encoded? I know the dirty way of doing it is to get the string character between =?utf-8?B? xxx ?= and decoding that. But I have a program where I can get encoded strings like
=?utf-8?Bxxxx?= =?UTF-8?B?xxxx?= ...
Right now I'm doing something like this
If codedString.ToUpper().StartsWith("=?UTF-8?B?") Then
Dim temp As String = codedString.SubString(10)
Dim data = Convert.FromBase64String(temp)
Dim decodedString = ASCIIEncoding.ASCII.GetString(data)
'do something with decodedString
End If
But this doesn't work when the same string has multiple =?utf-8?B? encode like above. Also I can get strings with =?utf-8?Q encoding and =?windows-1252. Is there a way to tackle all of these encoding? I'm using Visual Studios 2017
I've never had trouble using this function to decode a email field value:
It finds matching utf-8 strings for types B or Q, and if type B, runs FromBase64String.
I'm sure you can manipulate for windows-1252.
Private Function DecodeEmailField(byVal strString as String) as String
DecodeEmailField = strString.toString()
Dim strMatch
Dim arrEncodeTypes = New String() {"B","Q"}
Dim strEncodeType as String
For Each strEncodeType in arrEncodeTypes
Dim objRegexB as RegEx = new RegEx("(?:\=\?utf\-8\?" & strEncodeType & "\?)(?:.+?)(?:\?=\s)", _
RegexOptions.Multiline or RegexOptions.IgnoreCase)
if (objRegexB.IsMatch(DecodeEmailField)) then
Dim thisMatch as Match = objRegexB.Match(DecodeEmailField)
For Each strMatch in thisMatch.Groups
Dim strMatchHold as String = strMatch.toString().Substring(("=?utf-8?" & strEncodeType & "?").length)
strMatchHold = strMatchHold.SubString(0,(strMatchHold.Length)-("?= ".Length))
If strEncodeType = "B" Then
Dim data() As Byte = System.Convert.FromBase64String(strMatchHold)
strMatchHold = System.Text.UTF8Encoding.UTF8.GetString(data)
End If
DecodeEmailField = Replace(DecodeEmailField,strMatch.toString(),strMatchHold)
Next
End If
Next
End Function

(VB.NET) Find all duplicates in a list of objects based on multiple properties

I have a list of CommissionStatement objects which i created. I need to create a new list which only holds the duplicates found in this list based on 3 properties: Firm; Provider; and Total (ie each of these 3 have to be the same in 2 or more objects for it to be recognized as a duplicate)
Object is a simple object of strings at the moment.
Private Class CommissionStatement
Property Provider As String
Property Firm As String
Property Source As String
Property Media As String
Property Total As String
Property Received As String
End Class
I have a list of all CommissionStatments as follows:
Dim fileLocation As String = importText.Text
Dim csvText As String = My.Computer.FileSystem.ReadAllText(fileLocation).Replace(", ", " ")
Dim providerString As String = ""
Dim allStatements = New List(Of CommissionStatement)
Dim countIndex As Integer = 0, maxIndex As Integer = csvText.Split(vbLf).Length
For Each line As String In csvText.Split(vbLf)
'' Remove the top row
countIndex += 1
If countIndex = 1 Then
Continue For
End If
statementProgress.Value = ((countIndex / maxIndex) * 100)
'' Build the New commissionStatement object and add it to the allStatements list
If Not line = "" Then
Dim commissionStatement = New CommissionStatement
With commissionStatement
.Provider = line.Split(",")(0)
.Firm = line.Split(",")(1)
.Source = line.Split(",")(2)
.Media = line.Split(",")(3)
.Total = line.Split(",")(4)
End With
providerString &= commissionStatement.Provider & ","
allStatements.Add(commissionStatement)
End If
Next
First post on StackOverflow so sorry if its not very clear! The duplicate list needs to also be a list of CommissionStatements which contain the duplicates from the allStatements list based on Firm Provider and Total
Your best bet is to use a lambda expression. The function below should do what you ask.
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
Return allStatements.FindAll(Function(x) x.Firm = tempStatement.Firm And x.Provider = tempStatement.Provider And x.Total = tempStatement.Total)
End Function
And use it like this..
duplicatelist = GetDuplicateCommisionStatements(testCommisionStatement)
using your own object names of course.
Incidentally, you could shorten the sub using the With statement like below
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
With tempStatement
Return allStatements.FindAll(Function(x) x.Firm = .Firm And x.Provider = .Provider And x.Total = .Total)
End With
End Function

How to add a character to the beginging of each string in a list of strings

I have a simple list of strings and what i need to do is to add "#" to the beginning of each item and join the list to get something like: "#item1, #item2,...."
my code so far:
Dim list As New List(Of String)({"item1", "item2", "item3", "item4"})
' create a copy of list to prevent altering it
Dim listCopy As List(Of String) = list
For i As Integer = 0 To listCopy.Count - 1
list(i) = "#" & listCopy(i)
Next
Dim result As String = String.Join(", ", list.ToArray())
While this does the job but i feel that it's too much code for a simple function, the same thing can be done in python or javascript much easier like:
python:
copyList = [("#" + x) for x in list]
javascript:
copylist = list.map(function(x){return '#' + x})
Is there a similar function in vb.net?
Yes, you can use the LINQ Select method to achieve this:
Dim list As New List(Of String)({"item1", "item2", "item3", "item4"})
dim list1 = list.Select(function (i) "#" + i)
for each item in list1
Console.WriteLine(item)
next item
And the output is:
#item1
#item2
#item3
#item4
The result is an IEnumerable (Of String) object. If you want again a List (Of String) than use the ToList() extension method:
dim list1 = list.Select(function (i) "#" + i).ToList()
Use LINQ:
Dim result = (From s In list Select "#" & s)

String Array Thing!

Right - to start with, I'm entering unfamiliar areas with this - so please be kind!
I have a script that looks a little something like this:
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
Dim strOut As String = ""
Dim strWord As String
For Each strWord In astrWords
If strIn.ToLower.IndexOf(strWord.ToLower, 0) >= 0 Then
strOut = strWord.ToLower
Exit For
End If
Next
Return strOut
End Function
It's function is to check the input string and see if any of those 'astrWords' are in there and then return the value.
So I wrote a bit of code to dynamically create those words that goes something like this:
Dim extensionArray As String = ""
Dim count As Integer = 0
For Each item In lstExtentions.Items
If count = 0 Then
extensionArray = extensionArray & """." & item & """"
Else
extensionArray = extensionArray & ", ""." & item & """"
End If
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Obviously - it's creating that same array using list items. The output of that code is exactly the same as if I hard coded it - but when I change the first bit of code to:
Dim astrWords As String() = New String() {My.Settings.extensionArray}
instead of:
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
It starts looking for the whole statement instead of looping through each individual one?
I think it has something to do with having brackets on the end of the word string - but I'm lost!
Any help appreciated :)
When you use the string from the settings in the literal array, it's just as if you used a single strings containing the delimited strings:
Dim astrWords As String() = New String() {"""bak"", ""log"", ""dfd"""}
What you probably want to do is to put a comma separated string like "bak,log,dfd" in the settings, then you can split it to get it as an array:
Dim astrWords As String() = My.Settings.extensionArray.Split(","C)
You need to set extensionArray up as a string array instead of simply a string.
Note that
Dim something as String
... defines a single string, but
Dim somethingElse as String()
... defines a whole array of strings.
I think with your code, you need something like:
Dim extensionArray As String() = new String(lstExtensions.Items)
Dim count As Integer = 0
For Each item In lstExtentions.Items
extensionArray(count) = item
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Then at the start of checkString you need something like
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = My.Settings.extensionArray
...
There also might be an even easier way to turn lstExtentions.Items into an Array if Items has a 'ToArray()' method, but I'm not sure what Type you are using there...
What you've done is created a single string containing all 3 words. You need to create an array of strings.
New String() {"bak", "log", "dfd"}
means create a new array of strings containing the 3 strings values "bak", "log" and "dfd".
New String() {My.Settings.extensionArray}
means create a new array of strings containing just one value which is the contents of extensionArray. (Which you have set to ""bak", "log", "dfd""). Note this is one string, not an array of strings. You can't just create 1 string with commas in it, you need to create an array of strings.
If you want to create your array dynamically, you need to define it like this:
Dim astrWords As String() = New String(3)
This creates an array with 3 empty spaces.
You can then assign a string to each space by doing this:
astrWords(0) = "bak"
astrWords(1) = "log"
astrWords(2) = "dfd"
You could do that bit in a for loop:
Dim count As Integer = 0
For Each item In lstExtentions.Items
astrWords(count) = item
count = count + 1
Next
Alternatively, you could look at using a generic collection. That way you could use the Add() method to add multiple strings to it
I think you want your extensionArray to be of type String() and not String. When you are trying to initialize the new array, the initializer doesn't know to parse out multiple values. It just sees your single string.