Length of 2D String list does not return the right value - vb.net

I have a problem when I use .count in my 2D String list. This is the code:
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
Dim s As String
accountCounter = 0
For Each s In readText
accountList.Add(New List(Of String))
accountList.Add(New List(Of String))
accountList.Add(New List(Of String))
accountList(accountCounter).Add(s.Split(",")(0))
accountList(accountCounter).Add(s.Split(",")(1))
accountList(accountCounter).Add(s.Split(",")(2))
accountCounter += 1
Next
print_logs(accountList.count)
End If
The result is this:
{{name,email,password},{name2,email2,password2},{name3,email3,password3},{name4,email4,password4}}
beacuse in the file there are the following lines:
name,email,password
name2,email2,password2
name3,email3,password3
name4,email4,password4
But data is not the problem, the real problem is the Count method, it returns (12). I think that it returns 4 * 3 result, because if I add this in the code:
print_logs(accountList(0).Count)
it correctly returns 3.
So, how can I just return 4?

In this code you create three new rows everytime you do an iteration... If there are four lines in your text files then you will create twelve...
Do this instead :
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
Dim s As String
accountCounter = 0
For Each s In readText
accountList.Add(New List(Of String))
accountList(accountCounter).Add(s.Split(",")(0))
accountList(accountCounter).Add(s.Split(",")(1))
accountList(accountCounter).Add(s.Split(",")(2))
accountCounter += 1
Next
print_logs(accountList.count)
End If
And if you want to make it even better :
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
For Each s As String In readText
Dim newList = New List(Of String)
newList.Add(s.Split(",")(0))
newList.Add(s.Split(",")(1))
newList.Add(s.Split(",")(2))
accountList.Add(newList)
Next
print_logs(accountList.count)
End If

Related

Searching Multiple strings with 1st criteria, then searching those returned values with a different criteria and so on

so..
I have a txt file with hundreds of sentences or strings.
I also have 4 comboboxes with options that a user can select from and
each combobox is part of a different selection criteria. They may or may not use all the comboboxes.
When a user selects an option from any combobox I use a For..Next statement to run through the txt file and pick out all the strings that contain or match whatever the user selected. It then displays those strings for the user to see, so that if they wanted to they could further narrow down the search from that point by using the 3 remaining comboboxes making it easier to find what they want.
I can achieve this by using lots of IF statements within the for loop but is that the only way?
No, there are other ways. You can leverage LINQ to get rid of some of those if statements:
Private _lstLinesInFile As List(Of String) = New List(Of String)
Private Function AddClause(ByVal qryTarget As IEnumerable(Of String), ByVal strToken As String) As IEnumerable(Of String)
If Not String.IsNullOrWhiteSpace(strToken) Then
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.Contains(strToken))
End If
Return qryTarget
End Function
Public Sub YourEventHandler()
'Start Mock
Dim strComboBox1Value As String = "Test"
Dim strComboBox2Value As String = "Stack"
Dim strComboBox3Value As String = String.Empty
Dim strComboBox4Value As String = Nothing
'End Mock
If _lstLinesInFile.Count = 0 Then
'Only load from the file once.
_lstLinesInFile = IO.File.ReadAllLines("C:\Temp\Test.txt").ToList()
End If
Dim qryTarget As IEnumerable(Of String) = (From strTarget In _lstLinesInFile)
'Assumes you don't have to match tokens that are split by line breaks.
qryTarget = AddClause(qryTarget, strComboBox1Value)
qryTarget = AddClause(qryTarget, strComboBox2Value)
qryTarget = AddClause(qryTarget, strComboBox3Value)
qryTarget = AddClause(qryTarget, strComboBox4Value)
Dim lstResults As List(Of String) = qryTarget.ToList()
End Sub
Keep in mind this is case sensitive so you may want to throw in some .ToLower() calls in there:
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.ToLower().Contains(strToken.ToLower()))
I think a compound If statement is the simplest:
Dim strLines() As String = IO.File.ReadAllText(strFilename).Split(vbCrLf)
Dim strSearchTerm1 As String = "Foo"
Dim strSearchTerm2 As String = "Bar"
Dim strSearchTerm3 As String = "Two"
Dim strSearchTerm4 As String = ""
Dim lstOutput As New List(Of String)
For Each s As String In strLines
If s.Contains(strSearchTerm1) AndAlso
s.Contains(strSearchTerm2) AndAlso
s.Contains(strSearchTerm3) AndAlso
s.Contains(strSearchTerm4) Then
lstOutput.Add(s)
End If
Next

Split() doesn't work properly

well I'm doing a computing assessment and well I've ran into an issue with splitting a string. For some reason when the string splits the array stores the whole thing in Variable(0). The error that occurs is when it tries to assign TicketID(Index) a value, it says that the array is out of bound.
Here's the code:
Private Sub ReadInformation(ByRef TicketID() As String, CustomerID() As String, PurchaseMethod() As Char, NumberOfTickets() As Integer, FileName As String)
Dim Line, TextArray(3) As String
Dim Index As Integer
FileOpen(1, FileName, OpenMode.Input)
For Index = 0 To 499
Input(1, Line)
TextArray = Line.Split(",")
CustomerID(Index) = TextArray(0)
TicketID(Index) = TextArray(1)
NumberOfTickets(Index) = TextArray(2)
PurchaseMethod(Index) = TextArray(3)
MessageBox.Show(CustomerID(Index))
Next
FileClose()
End Sub
Here's the first 10 lines of the TextFile I'm trying to read:
C001,F3,10,S
C002,F3,2,O
C003,F3,3,S
C004,W2,9,S
C005,T3,10,S
C006,F3,2,S
C007,W1,3,O
C008,W3,1,O
C009,T2,2,S
C010,F2,9,O
Here's the Error Message I receive:
Error Message
I would use some Lists instead of arrays. In this way you don't have to worry about length of the arrays or if there are fewer lines than 500. Of course, using the more advanced NET Framework methods of the File.IO namespace is a must
Private Sub ReadInformation(TicketID As List(Of String), _
CustomerID As List(Of String), _
PurchaseMethod As List(Of Char), _
NumberOfTickets As List(Of Integer), _
FileName As String)
for each line in File.ReadLines(FileName)
Dim TextArray = Line.Split(","c)
if TextArray.Length > 3 Then
CustomerID.Add(TextArray(0))
TicketID.Add(TextArray(1))
' This line works just because you have Option Strict Off
' It should be changed as soon as possible
NumberOfTickets.Add(TextArray(2))
PurchaseMethod.Add(TextArray(3))
End If
Next
End Sub
You can call this version of your code declaring the 4 lists
Dim TicketID = New List(Of String)()
Dim CustomerID = New List(Of String)()
Dim PurchaseMethod = New List(Of Char)()
Dim NumberOfTickets = New List(Of Integer)()
ReadInformation(TicketID, CustomerID, PurchaseMethod, NumberOfTickets, FileName)
Another approach more Object Oriented is to create a class that represent a line of your data. Inside the loop you create instances of that class and add the instance to a single List
Public Class CustomerData
Public Property TicketID As String
Public Property CustomerID As String
Public Property NumberOfTickets As Integer
Public Property PurchaseMethod As Char
End Class
Now the loop becomes
Private Function ReadInformation(FileName As String) as List(Of CustomerData)
Dim custData = New List(Of CustomerData)()
For Each line in File.ReadLines(FileName)
Dim TextArray = Line.Split(","c)
if TextArray.Length > 3 Then
Dim data = new CustomerData()
data.CustomerID = TextArray(0)
data.TicketID = TextArray(1)
data.NumberOfTickets = TextArray(2)
data.PurchaseMethod = TextArray(3)
custData.Add(data)
End If
Next
return custData
End Function
This version requires the declaration of just one list
You can call this version of your code passing just the filename and receiving the result fo the function
Dim customers = ReadInformation(FileName)
For Each cust in customers
Console.WriteLine(cust.CustomerID)
...
Next
Or use it as an array
Dim theFirstCustomer = customers[0]
Console.WriteLine(theFirstCustomer.CustomerID)

Splitting file into parts for dictionary use

I have an uploaded file, displaying
Han 33.3
Han 5.66
Han 8.3
Chewbacca 99.4
Chewbacca 100.3
Chewbacca 98.1
I need to make an average for each han and Chewbacca using a dictionary, but first I have to split the list in order to do that. How do I split them for this purpose.
I'm making the assumption that the whitespace between the name and quantity is a single space. I'm also calling your values "scores" and Han and Chewbacca "players" for my example solution. The result splits the line into individual key-value pairs; each key represents the list of values found; it:
Imports System.IO
Dim pathToYourFile As String = "Path to your file with file name"
Dim f As StreamReader = File.OpenText(pathToYourFile)
Dim fileText As String = f.ReadToEnd
f.Close()
Dim singleSpace As String = " " 'single space between quotes
Dim playerScores As New SortedDictionary(Of String, List(Of Double))
Dim lines() As String = fileText.Split(vbCrLf.ToCharArray())
For i As Integer = 0 To lines.Length - 1
Dim scoreLine() As String = lines(i).Split(" ".ToCharArray())
Dim playerName As String = scoreLine(0)
Dim score As Double = Double.Parse(scoreLine(1))
If playerScores.ContainsKey(playerName) Then
playerScores(playerName).Add(score)
Else
Dim list As New List(Of Double)
list.Add(score)
playerScores.Add(playerName, list)
End If
Next i
Try this:
Public Class DataClass
Public Property Name() As String
Public Property Value() As Decimal
End Class
' ...
Public Shared Function GetAverageDict(lines As IEnumerable(Of String)) _
As Dictionary(Of String, Decimal)
Dim lst As New List(Of DataClass)()
For Each line As String In lines
Dim lastSpaceIndex = line.LastIndexOf(" ")
If (lastSpaceIndex >= 0) Then
Dim name = line.Substring(0, lastSpaceIndex).Trim()
Dim value = Decimal.Parse(line.Substring(lastSpaceIndex + 1), _
System.Globalization.CultureInfo.InvariantCulture)
lst.Add(New DataClass() With { .Name = name, .Value = value })
End If
Next
Dim averages = From g In From x In lst _
Group x By key = x.Name _
Select New With { .Name = key, _
.Average = Group.Average(Function(y) y.Value) }
Return averages.ToDictionary(Function(x) x.Name, Function(y) y.Average)
End Function
The function first gets the parts from each line. It assumes that the last space is the separator between the parts. This way, the name can also contain space characters.
The data is collected in a list that is afterwards grouped by the name. By calling ToDictionary the result of the grouping operation is converted in a dictionary.
Call the function like this:
Dim dict = GetAverageDict(System.IO.File.GetLines(filePath))

Count occurance of specific words in a text file in vb.net

I'm trying to count the number of an item in a text file, by counting each instance the item was entered into the file earlier on in the program.
I already have the text read from the file and in a text box. The problem is that my current code was just counting the characters in the textbox and not the number of times my desired word was in the file.
For Each desiredword As String In txtContentofFile.Text
intdesiredword = intdesiredword + 1
txtdesiredwordcount.Text = intdesiredword
Next
This counts the characters in the textbox instead of counting the number of desired words. I tried repeatedly before asking help and searched extensively, but I just don't understand what's wrong with my code. Please help :)
You can use Split Function :
C#:
int count = txtContentofFile.Text.Split(desiredword).Length - 1;
VB.net:
Dim count As Integer = txtContentofFile.Text.Split(desiredword).Length - 1
I prefer to use Regular Expressions in this type of situation. They are very tricky to understand but they are extremely powerful and typically faster than other string manipulation techniques.
Dim AllMatchResults As MatchCollection
Try
Dim RegexObj As New Regex(desiredword)
AllMatchResults = RegexObj.Matches(txtContentofFile.Text)
If AllMatchResults.Count > 0 Then
' Access individual matches using AllMatchResults.Item[]
Else
' Match attempt failed
End If
Catch ex As ArgumentException
'Syntax error in the regular expression
End Try
In your case you are looking for the value from AllMatchResults.Count.
Using a great Regular Expression tool like RegexBuddy to build and test the expressions is a great help too. (The above code snippet was generated by RegexBuddy!)
Try this:
Dim text As String = IO.File.ReadAllText("C:\file.txt")
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))
'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))
findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)
Function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
Dim dResult As New Dictionary(Of String, List(Of Integer))()
Dim i As Integer = 0
For Each s As String In wordsToSearch
dResult.Add(s, New List(Of Integer))
While i >= 0 AndAlso i < allWords.Count
i = allWords.IndexOf(s, i)
If i >= 0 Then dResult(s).Add(i)
i += 1
End While
Next
Return dResult
End Function
You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.
Try the following code
Function word_frequency(word_ As String, input As String) As Integer
Dim ct = 0
Try
Dim wLEN = word_.Length
Do While input.IndexOf(word_) <> -1
Dim idx = input.IndexOf(word_) + wLEN
ct += 1
input = input.Substring(idx)
Loop
Catch ex As Exception
End Try
Return ct
End Function

How can I search an array in VB.NET?

I want to be able to effectively search an array for the contents of a string.
Example:
dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}
I pass the value is "ra" and I want it to return the index of 2 and 3.
How can I do this in VB.NET?
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.
In case you were looking for an older version of .NET then use:
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result As New List(Of Integer)
For i As Integer = 0 To arr.Length
If arr(i).Contains("ra") Then result.Add(i)
Next
End Sub
End Module
check this..
string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
Array.IndexOf(strArray, "C"); // not found, returns -1
Array.IndexOf(strArray, "CDE"); // found, returns index
compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.
simple eg.
dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)
if aNames(x) = sFind then y = x
y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:
z = 1
for x = 1 to length(aNames)
if aNames(x) = sFind then
aIndexes(z) = x
z = z + 1
endif
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Never use .ToLower and .ToUpper.
I just had problems in Turkey where there are 4 "i" letters. When using ToUpper I got the wrong "Ì" one and it fails.
Use invariant string comparisons:
Const LNK as String = "LINK"
Dim myString = "Link"
Bad:
If myString.ToUpper = LNK Then...
Good and works in the entire world:
If String.Equals(myString, LNK , StringComparison.InvariantCultureIgnoreCase) Then...
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))