For each using linq how to use else - vb.net

i have code that is checking for specific files and then if condition is fulfilled its going in to stats.matching.... I am using this for each linq:
For Each file As String In From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where ftpFile.Contains(currentReportName)
Select file1
Stats.MatchingFiles.Add(file)
Next
The question is how to implement else here.

So you want to fill another collection with files that don't contain the word.
Dim matching = From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where ftpFile.Contains(currentReportName)
Dim mismatching = From file1 In Stats.FoundFiles
Let ftpFile = Utils.ToLowerWithoutSpaces(file1)
Where Not ftpFile.Contains(currentReportName)
For Each file As String In matching
Stats.MatchingFiles.Add(file)
Next
For Each file As String In mismatching
Stats.MismatchingFiles.Add(file)
Next
That is the simple solution, you could also use Except which is more efficient:
Dim mismatching = Stats.FoundFiles.Except(matching)

I think in your case original For Each loop with If... Else will be simple enough approach
And loop a Stats.FoundFile only once
For Each file As String In Stats.FoundFiles
Dim ftpFile As String = Utils.ToLowerWithoutSpaces(file)
If ftpFile.Contains(currentReportName) = True Then
Stats.MatchingFiles.Add(file)
Else
Stats.MismatchingFiles.Add(file)
End If
Next
Or if you are fan of LINQ and must to use it, then you can play with Aggregate extension method
Stats.FoundFiles.Aggregate(String.Empty,
Function(seed, file)
If Utils.ToLowerWithoutSpaces(file).Contains(file) Then
Stats.MatchingFiles.Add(file)
Else
Stats.MismatchingFiles.Add(file)
End If
Return String.Empty
End Function)

Related

Reading text from one file, to check other text file for matches

So I'm new to VB.NET, and I'm trying to read through 2 separate text files. File2 first & pulling a variable from it. I then want to take that variable, and check File1 to see if the string matches. Both files are relatively large, and I have to trim part of the string from the beginning, hence the multiple splits. So currently, this is what I have. But where I'm getting hung up is, how do I get it to check every line to see if it matches with the other file?
Public Function FileWriteTest()
Dim file1 = My.Computer.FileSystem.OpenTextFileReader(path)
Dim file2 = My.Computer.FileSystem.OpenTextFileReader(path)
Do Until file2.EndOfStream
Dim line = file2.ReadLine()
Dim noWhiteSpace As New String(line.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
Dim split1 = Split(noWhiteSpace, "=")
Dim splitStr = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter = Split(splitStr, "Module")
Dim finalParameter = parameter(1)
End If
'Here is where I'm not sure how to continue. I have trimmed the variable to where I would like to check with the other file.
'But i'm not sure how to continue from here.
Here are a couple of cleanup notes:
Get the lines of your first file by using IO.File.ReadAllLines (documentation)
Get the text of the second file by using IO.File.ReadAllText (documentation)
Use String.Replace (documentation) instead of Char.IsWhitespace, this is quicker and much more obvious as to what is going on
Use String.Split (documentation) instead of Split (because this is 2021 not 1994).
In terms of what you would do next, you would call String.IndexOf (documentation) on the second file's text, passing your variable value, to see if it returns a value greater than -1. If it does, then you know where at in the file the value exists.
Here is an example:
Dim file1() As String = IO.File.ReadAllLines("path to file 1")
Dim file2 As String = IO.File.ReadAllText("path to file 2")
For Each line In file1
Dim noWhiteSpace As String = line.Replace(" ", String.Empty)
Dim split1() As String = noWhiteSpace.Split("=")
If (splitStr.Length > 0) Then
Dim splitStr As String = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter() As String = splitStr.Split("Module")
If (parameter.Length > 0) Then
Dim finalParameter As String = parameter(0)
Dim index As Integer = file2.IndexOf(finalParameter)
If (index > -1) Then
' finalParameter is in file2
End If
End If
End If
End If
Next

How do I read a tab delimited file to find the line which has a known value?

I have a tab delimited file which has data like this...
022j<TAB>10.375
023j<TAB>12.365
024j<TAB>15.230
NOTE: this will not let me post as it is... each 02xj is a different line in the text file. It
EG: 023j is input into a textbox.
Need to find the value associated with the input; 12.365 in this case.
There are a few different files (some are encoded 012j, 012#, 012$ etc. which will correspond to different data.)
My head is exploding trying to find a way to take what I have in the textbox then read through and find the data I need.
I know this is easy, please nudge me in the right direction.
Here's your nudge. You should be able to use something like this:
Dim searchValue As Decimal = 023j 'or someTextBox.Text whatever
Dim searchField As Int32 = 0
Dim returnField As Int32 = 1
Dim returnValue As String = ""
Dim returnLineNumber as Int32 = 0
Using fileReader As New FileIO.TextFieldParser(YourFileNameWithPathAsString)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(vbTab)
While Not fileReader.EndOfData
Dim currentLine As String() = fileReader.ReadFields()
If currentLine(searchField) = searchValue Then
returnValue = currentLine(returnField)
returnLineNumber = fileReader.LineNumber
Exit While
End If
End While
End Using
Return returnValue 'or Return returnLineNumber if that is what you need
You should be able to make it a function and if no result is returned then check your next file.
I figured this out... so this is what I ended up doing.
First set up the streamreader
'set reader to read the file
Dim reader As New System.IO.StreamReader(filetoread)
Then loop through the file line by line, use contains to find the string to match. Do whatever trimming/extracting and you're there.
Do While reader.Peek() >= 0
line = reader.ReadLine
If line.Contains(TB_Input.Text) Then
s = Replace(line, TB_Input.Text, "")
s = Replace(s, vbTab, "")
TB_Length.Text = s
End If
Loop
I was leaking brain juice on this. Until someone basically said "just do it"... thanks I needed that.
I know there are things like variables I don't explain... I figured anyone looking will know, if that's a bad assumption let me know.
Thanks again

VBNET Reading a specific column on a line in a text file

I have saved written a text file and it currently reads:
"first","surname","pass"
I want to read the password column so the 3rd one and define that as a variable. Its basically for a login, if pass in text file matches the entered pass (from user).
I have searched for about an hour now and no luck. Could someone guide me to a correct path.
Thanks.
Simple example of reading a small file line by line and splitting each one into fields:
' get the values from the user somehow:
Dim first As String = "James"
Dim surname As String = "Bond"
Dim pass As String = "007"
Dim validated As Boolean = False ' assume wrong until proven otherwise
' check the file:
Dim fileName As String = "c:\some folder\path\somefile.txt"
Dim lines As New List(Of String)(System.IO.File.ReadAllLines(fileName))
For Each line As String In lines
Dim values() As String = line.Split(",")
If values.Length = 3 Then
If values(0).Trim(Chr(34)) = first AndAlso
values(1).Trim(Chr(34)) = surname AndAlso
values(2).Trim(Chr(34)) = pass Then
validated = True
Exit For
End If
End If
Next
' check the result
If validated Then
MessageBox.Show("Login Successful!")
Else
MessageBox.Show("Login Failed!")
End If
If this is a CSV file, as seems to be the case, then the easiest way to read it will be with the TextFieldParser class. The MSDN already provides an excellent example for how to use it to read a CSV file, so I won't bother reproducing it here.

My List(OF Strings) are being saved as system.string (Empty)

I'm trying to delete a selected row, then save the rest into a file. However, when I save it, it totally empties the file.
Console.Write("Please eneter the first name of the student you wish to search for: ")
searchfname = Console.ReadLine
searchfname = StrConv(searchfname, VbStrConv.ProperCase)
Console.Write("Please enter the second name of the student you wish to search for: ")
searchsname = Console.ReadLine
searchsname = StrConv(searchsname, VbStrConv.ProperCase)
Dim foundItem() As String = Nothing
Dim foundline As String = Nothing
Dim fnsearch As String = String.Join(searchfname, searchsname)
Dim lines As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
For Each line As String In lines
If searchfname = item(3) And searchsname = item(4) Then
Console.WriteLine(line)
Console.WriteLine()
Console.WriteLine("Are you sure you wish to delete this record? (y/n)")
End If
Dim answer As String
answer = Console.ReadLine
If answer = "y" Or answer = "Y" Then
Console.Clear()
lines.Remove(line)
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
sw.WriteLine(lines.ToString)
End Using
ElseIf answer = "n" Or answer = "N" Then
staffmenu()
End If
Next
Look at this line in your code:
sw.WriteLine(lines.ToString)
Extract the lines.ToString expression from that statement. The result of that expression is "System.String". You are telling your stream writer to write the text "System.String" to the file.
To fix it, you need something more like this:
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
For Each line As String In lines
sw.WriteLine(line)
Next line
End Using
The method List(Of T).ToString does not produce a value that includes the elements of the collection. Instead it will just return the type name.
The API you are looking for is File.WriteAllLines. Using this instead of StreamWriter and the Using block
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", lines)
I can see that this issue can be resolved from the given answers and comment, but I would like to add an alternative to use Join function in writing to a file. Try like this may be of help:
Using sw As New StreamWriter(.....)
sw.WriteLine(Join(lines.ToArray(), Environment.NewLine))
End Using
Since using VB.Net, this is a vb.net specific solution can not be used in C#. For C#, use string.join instead.
Hope it helps too!

String.Contains Function in Visual Basic 2008 or 2012

How do I find a unique string that contains in a single .txt file with different strings in each line?
Example:
The .txt file contains the following
012345
023456
034567
045678
056789
Then I want to find one of the set of numbers.
This is what I want to happen~
Dim stN As String = TextBox1.Text
If stN.contains(.txt file) Then
'Anything to do here
Else
MsgBox("Your input number is incorrect", "ERROR")
End If
I assume your pseudo code should be the other way around: If .txt-file.Contains(stN) Then.
So you want to know if a string equals one line of a text-file:
Dim lines = File.ReadLines(path)
Dim fileContainsLine = lines.Any(Function(l) l.Trim.Equals(TextBox1.Text, StringComparison.OrdinalIgnoreCase))
If you don't want to compare case-insensitively use l==TextBox1.Text instead. If the Trim is also unnecessary you could simplify it to:
Dim fileContainsLine = lines.Contains(TextBox1.Text)
Here is a little Linqpad program, but you would probably want to read in the file one time and cache it.
Sub Main
If (CheckContains("023456")) Then
Console.WriteLine("True")
Else
Console.WriteLine("False")
End If
End Sub
Function CheckContains(inputVal as String) as Boolean
Dim query = From line In File.ReadAllLines("C:\code\so\sample.txt") _
Select line
return query.Contains(inputVal)
End Function