Search from a list of string() in VB.NET - vb.net

I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
If mylines.Contains("food") Then
MsgBox("Value Exist")
End If
But the problem is that I want to check if mylines() contains a line which starts with my value. I can get this value from a single line by mylines(0).StartsWith method. But how do I find a string from all the lines which is starting from some value, e.g. "mysearch" and then get that line number?
I am using a for loop to do so, but it is slow.
For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)
Next
Constrained to code for .NET 2.0, please.

Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:
Imports System.IO
Public Class Form1
Dim SearchString As String = ""
Dim Test() As String = File.ReadAllLines("Test.txt")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SearchString = "Food"
End Sub
Private Function StartsWith(s As String) As Boolean
Return s.StartsWith(SearchString)
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim SubTest() As String = Array.FindAll(Test, AddressOf StartsWith)
ListBox1.Items.AddRange(SubTest)
End Sub
End Class
When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.

I'm not a VB guy, but I think you could use Linq:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
??? = mylines.Where(Function(s) s.StartWith("food")) //not sure of the return type
Check out: How do I append a 'where' clause using VB.NET and LINQ?

Related

Method for comparing text boxes in vb.net

I need help, so I can compare the text from the text booths that are in these 3 groupboxes.
This is what my form looks like:
Private Sub frmCompareAdress_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim firstGroupBoxFields() As String = {TextBoxVorname1.Text, TextBoxName1.Text, TextBoxStrasse1.Text, TextBoxPLZ1.Text, TextBoxOrt1.Text, TextBoxTelefon1.Text}
Dim secondGroupBoxFields() As String = {TextBoxVorname2.Text, TextBoxName2.Text, TextBoxStrasse2.Text, TextBoxPLZ2.Text, TextBoxOrt2.Text, TextBoxTelefon2.Text}
Dim thirdGroupBoxFields() As String = {TextBoxVorname3.Text, TextBoxName3.Text, TextBoxStrasse3.Text,TextBoxNr3.Text, TextBoxPLZ3.Text, TextBoxOrt3.Text, TextBoxTelefon3.Text}
ComparisonFieldsfirstGroupBoxFields, secondGroupBoxFields, thirdGroupBoxFields)
End Sub
Public Sub ComparisonFields(ByVal firstGBFields() As String, secondGBFields() As String, thirdGBFields() As String)
Dim notCompareFileds = String.Join(", ", firstGBFields.Except(secondGBFields))
'what to do next? I'm a little confused if I'm on the right track
End Sub
Now if, for example, the textBox1Vorname.Text is different from the textBox2Vorname.Text or textBox3Vorname.Text, I want to mark them in red.
I imagined it in a way, to compare as an array, and I put it in 3 array values from textboxes.
Can anyone help me further with this function?
Thank you for your help.
Public Shared Function HaveSameText(ParamArray controls() As Control) As Boolean
Return controls.All(Function(c) c.Text = controls(0).Text)
End Function
Public Shared Sub ColorAllRed(ParamArray controls() As Control)
For Each c In controls
c.ForeColor = Color.Red
Next
End Sub
Public Shared Sub ColorAllRedIfNotSameText(ParamArray controls() As Control)
If Not HaveSameText(controls) Then ColorAllRed(controls)
End Sub
Private Sub frmCompareAdress_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ColorAllRedIfNotSameText(TextBoxVorname1, TextBoxVorname2, TextBoxVorname3)
ColorAllRedIfNotSameText(TextBoxName1, TextBoxName2, TextBoxName3)
ColorAllRedIfNotSameText(TextBoxStrasse1, TextBoxStrasse2, TextBoxStrasse3)
ColorAllRedIfNotSameText(TextBoxPLZ1, TextBoxPLZ2, TextBoxPLZ3)
ColorAllRedIfNotSameText(TextBoxOrt1, TextBoxOrt2, TextBoxOrt3)
ColorAllRedIfNotSameText(TextBoxTelefon1, TextBoxTelefon2, TextBoxTelefon3)
End Sub

Value of type string() cannot be converted to string

I keep getting this error, I tried all I could but it still says "Value type of String() cannot be converted to string."
Here is the code:
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Sub New()
InitializeComponent()
RAN = New Random
WB = New WebClient
End Sub
Private Const IDNum As String = "https://example.com/Data.php"
Private WB As WebClient
Private RAN As Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Account As String() = WB.DownloadString(IDNum).Split(Environment.NewLine)
AccSplit(Account(RAN.Next(1, Account.Length)))
End Sub
Private Sub AccSplit(ByVal Account As String)
TextBox2.Text = Account.Split()
End Sub
When you call Split here:
TextBox2.Text = Account.Split()
You are getting a String array back. Calling Split with no arguments will split the String on whitespace characters. For instance, this:
Dim arr = "Hello World".Split()
is equivalent to this:
Dim arr = {"Hello", "World"}
The Text property of a TextBox is type String, so you can't assign a String array to it. That doesn't make sense. If you want to fry an egg, do you put am egg carton in the pan? The correct course of action depends on what you're actually trying to achieve. If you just want that String displayed in the TextBox then do this:
TextBox2.Text = Account
You could also do this:
TextBox2.Lines = Account.Split()
to display the array with the elements on separate lines in the TexTbox, which assumes that you have set its Multiline property to True.
TextBox2.Text is a string. The string.Split() function returns an array of strings (shown by Visual Studio as a string()). Those types don't match up. You can't just assign an array to a string. I might ask if you wanted this:
TextBox2.Text = String.Join(",", Account.Split())
That will at least compile. But it makes no sense... why split a string, just to join it back again?

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

How to do format check on string?vb.net

How do check that a string only consists of letters?########################################################################################################################################################################################################################################################
Here's a way to check if a string contains only letters:
Dim text As String = "abcd"
Dim flag As Boolean = text.AsEnumerable().All(Function(c As Char) Char.IsLetter(c))
You would use String.Contains() This exsplains how to use it, http://vb.net-informations.com/string/vb.net_String_Contains.htm
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
If str.Contains("TOP") = True Then
MsgBox("The string Contains() 'TOP' ")
Else
MsgBox("The String does not Contains() 'TOP'")
End If
End Sub
End Class
Edit: I'm not sure why your post includes a lot of #'s, is it an example of the text your looking to check over? :3
Public Function isValid(ByVal str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
Return reg.IsMatch(str)
End Function
This could possibly be the solution your after.
You want to use a regular expression like in this question:
C# Regex: Checking for "a-z" and "A-Z"
The vb should be very similar:
private function isValid(byval str as String) as Boolean
return Regex.IsMatch(str, #"^[a-zA-Z]+$")
End Function

Using the Content of Textbox as a variable in VB (2012)

In the code below b textbox will contain the string "a.text" what I want b textbox to be the evaluation of the content of the string "a.text" which is the word Test. Please don't suggest:
b.text = a.text
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim t As String
a.Text = "Test"
t = "a.text"
b.Text = t
End Sub
End Class
Check out Controls collection of your form. You can find an item based on its name.
Also check out this answer
VB .NET Access a class property by string value
So, you could take your string, split it by the ".", find the control using the Controls Collection, and then get the property using the second half of your string using Reflection.
Of course, if you are just looking for the Text of the textbox, you just need to use the collection and forget the reflection. Like this..
For i As Integer = 1 To 25
.fields("Field" & i).value = Me.Controls("QAR" & i).Text
Next
You can do what you asked for using Reflection ... I'm not an enormous fan of it for something like this, but here's how it would look in your code:
Imports System.Reflection
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
a.Text = "Hello"
Dim t As String = "a.Text"
b.Text = DirectCast(SetValue(t), String)
End Sub
Public Function SetValue(ByVal name As String) As Object
Dim ctrl As Control = Me.Controls(name.Split("."c)(0))
Return ctrl.GetType().GetProperty(name.Split("."c)(1)).GetValue(ctrl, Nothing)
End Function
End Class
This would set textbox a's value to "Hello" and then copy that to textbox b using the reflection method.
Hope this helps!