Collection to string() convertion in vb.net - vb.net

I'm a beginner.my question is,
I have an observablecollection(of string)
How can I add those collection's each elements as an array of string elements
Using for loop?
Dim obsv as new observablecollection(of string) // has some collection of string
For each str in obsv
// How can I add that str into string Array
Next

You can use LINQ .ToArray() method. Or use the Item[Int32] property.
Dim s As ObservableCollection(Of String)
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
And here is a complete working code snippet:
Imports System
Imports System.Collections.ObjectModel
Imports System.Linq
Public Module Module1
Public Sub Main()
Dim s As New ObservableCollection(Of String)()
s.Add("Hello")
s.Add("World")
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
Console.WriteLine("First array:")
Console.WriteLine(String.Join(", ", arr1))
Console.WriteLine()
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
Console.WriteLine("Second array:")
Console.WriteLine(String.Join(", ", arr2))
End Sub
End Module
Output is:
First array:
Hello, World
Second array:
Hello, World
Or if you want to use For Each loop, you can do it like that:
Dim arr2(s.Count - 1) As String
Dim i As Integer = 0
For Each str In s
arr2(i) = str
i += 1
Next

Related

Index of line textfile using StreamReader vb.net

How can I use this code?
TextBox1.Text = Array.FindIndex(linestring, Function(s) s.Contains(something))
but to use the code, without a word, and to display my array index following the code below:
Dim lines As New List(Of String)
Using reader As New StreamReader(My.Application.Info.DirectoryPath + ("\Data.txt"))
Dim line As String
Do Until line.StartsWith(endPrefix)
lines.Add(line)
line = reader.ReadLine()
'maybe here index of array
Loop
so how do I use this to get the line index from my text files?
Here is an example which uses the File.ReadLines method (which enumerates the lines of a file) where you can pass the predicate for the comparison to get the line number (starting at 1) of the first match:
Imports System.IO
Module Module1
Function FindLineNumber(sourceFile As String, textToFind As String, predicate As Func(Of String, String, Boolean)) As Integer
Dim lineNo = 1
For Each l In File.ReadLines(sourceFile)
If predicate(l, textToFind) Then
Return lineNo
End If
lineNo += 1
Next
Return -1
End Function
Sub Main()
' File to look in:
Dim src = "C:\temp\population.csv"
' Text to find:
Dim find = "133"
Dim lineNum = FindLineNumber(src, find, Function(a, b) a.Contains(b))
If lineNum > 0 Then
Console.WriteLine($"""{find}"" found at line {lineNum}.")
Else
Console.WriteLine($"""{find}"" not found.")
End If
Console.ReadLine()
End Sub
End Module

How to divide a string by another string using Split in VB.Net? [duplicate]

This question already has an answer here:
VB.NET String.Split method?
(1 answer)
Closed 3 years ago.
I am trying to divide a string similar to this:
"<span>1</span> - Selection"
And get the value that is enclosed between the <span>.
In JavaScript I do this:
var example= "<span>1</span> - selection";
var separation= example.replace("</span>","<span>").split("<span>");
console.log("Split: ",separation);
//The result is ["","1"," - Selección"]
console.log("Value that I want: ",separation[1]); //I get the value that I need
And that's it that I need to do but in Visual .NET, but it doesn't work for me.
I try:
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
or sending all the </span> replaced in the string to just do:
Dim WordString As String = "<span>1<span> - Selection"
Dim idSelection As String() = WordString.Split("<span>")
But in the position (1) I always get "span>1", and I can't do the split like in JS
How can I do it correctly?
To simulate the code VB.Net use https://dotnetfiddle.net/
The code:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
Console.WriteLine(idSelection(1))
End Sub
End Module
You have to use Split(String[], StringSplitOptions) to split using a string. So you can use the following solution:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split({"<span>"}, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine(idSelection(0))
End Sub
End Module
demo on dotnetfiddle.net
You can also use a solution using a regular expression with a positiv lookahead and lookbehind:
Imports System
Imports System.Text.RegularExpressions
Public Module Module1
Public Sub Main()
Dim rgx As New Regex("(?<=<span>)(.+)(?=</span>)")
Dim WordString As String = "<span>1</span> - Selection"
If rgx.IsMatch(WordString) Then
Console.WriteLine(rgx.Matches(WordString)(0))
End If
End Sub
End Module
demo on dotnetfiddle.net

Parse custom language syntax

I am developing a server-side scripting language which I intend to use on my private server. It is similar to PHP, and I know that I could easily use PHP instead but I'm just doing some programming for fun.
The syntax of basic commands in my language is as follows:
command_name "parameter1" : "parameter2" : "parameter3"
But it can also be like this when I want to join values for a parameter:
command_name "parameter1" : "param" & "eter2" : "par" & "amet" & "er3"
How would I go about parsing a string like the ones shown above (it will be perfectly typed, no syntax errors) to an object that has these properties
Custom class "Request"
Property "Command" as String, should be the "command_name" part
Property "Parameters" as String(), should be an array of Parameter objects
Shared Function FromString(s As String) as Request, this should accept a string in the language above and parse it to a Request object
Custom class "Parameter"
Property "Segments" as String(), for example "para", "mete", and "r3"
Sub New(ParamArray s as String()), this is how it should be generated from the code
It should be done in VB.NET and I am a moderate level programmer, so even if you just have an idea of how to attack this then please share it with me. I am very new to parsing complex data like this so I need a lot of help. Thanks so much!
Here is another method that is simpler.
Module Module1
Sub Main()
Dim inputs As String() = {"command_name ""parameter1"" : ""parameter2"" : ""parameter3""", "command_name ""parameter1"" : ""param"" & ""eter2"" : ""par"" & ""amet"" & ""er3"""}
For Each _input As String In inputs
Dim commandStr As String = _input.Substring(0, _input.IndexOf(" ")).Trim()
Dim parameters As String = _input.Substring(_input.IndexOf(" ")).Trim()
Dim parametersA As String() = parameters.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(Function(x) x.Trim()).ToArray()
Dim parametersB As String()() = parametersA.Select(Function(x) x.Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(Function(y) y.Trim(" """.ToCharArray())).ToArray()).ToArray()
Dim newCommand As New Command() With {.name = commandStr, .parameters = parametersB.Select(Function(x) New Parameter(x)).ToArray()}
Command.commands.Add(newCommand)
Next (_input)
Dim z = Command.commands
End Sub
End Module
Public Class Command
Public Shared commands As New List(Of Command)
Public name As String
Public parameters As Parameter()
End Class
Public Class Parameter
Sub New()
End Sub
Sub New(names As String())
Me.names = names
End Sub
Public names As String()
End Class
I figured it out myself
Module Module1
Sub Main()
Dim r As Request = Request.Parse(Console.ReadLine())
Console.WriteLine("The type of request is " & r.Name)
For Each p As Parameter In r.Parameters
Console.WriteLine("All segments inside of parameter " & r.Parameters.IndexOf(p).ToString)
For Each s As String In p.Segments
Console.WriteLine(" Segment " & p.Segments.IndexOf(s).ToString & " is " & s)
Next
Next
Main()
End Sub
Public Class Request
Public Name As String
Public Parameters As New List(Of Parameter)
Public Shared Function Parse(line As String)
Dim r As New Request
r.Name = line.Split(" ")(0)
Dim u As String = line.Substring(line.IndexOf(" "), line.Length - line.IndexOf(" "))
Dim p As String() = u.Split(":")
For Each n As String In p
Dim b As String() = n.Split("&")
Dim e As New List(Of String)
For Each m As String In b
Dim i As Integer = 0
Do Until i > m.Length - 1
If m(i) = ControlChars.Quote Then
Dim s As String = ""
i += 1
Do Until i > m.Length - 1 Or m(i) = ControlChars.Quote
s &= m(i)
i += 1
Loop
e.Add(s)
End If
i += 1
Loop
Next
r.Parameters.Add(New Parameter(e.ToArray))
Next
Return r
End Function
End Class
Public Class Parameter
Public Segments As New List(Of String)
Public Sub New(ParamArray s As String())
Segments = s.ToList
End Sub
End Class
End Module

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))