How to make a random string array in vb.net - arrays

I'm not sure if my title is exactly what I need so let me explain.
What I'm doing is making a "simple" game that list a US State (at random into a label) and then below the label is 5 Buttons of which I am trying to change the text to the buttons to random State Capital (all of the Capitals need to be random except for the correct one) After hours of researching with no luck it seems that I am not the only one trying get help with this. If you can help it would be great!
Private Class Players
Public Team As String
Public Name As String
Public Sub New(ByVal Team As String, ByVal Name As String)
Me.Team = Team
Me.Name = Name
End Sub
End Class
' Arraylist
Dim lstCapitals As New ArrayList
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim list As New List(Of Players)
' Capital Names
lstCapitals.Add("Montgomery")
lstCapitals.Add("Juneau")
lstCapitals.Add("Phoenix")
lstCapitals.Add("Little Rock")
lstCapitals.Add("Sacramento")
lstCapitals.Add("Denver")
lstCapitals.Add("Hartford")
' Random number generator
Dim randomInt As New Random
' Pulls a name randomly from the list
Dim stringname As String = lstCapitals.Item(randomInt.Next(0, 6))
'6 = lstCapitals.Count / one line up
' Show the name
'stateNamelbl.Show()
'NOT SURE IF I NEEDED THIS OR NOT THATS WHY ITS COMMENTED OUT
'Dim RandomList = From RndList In (From xitem In list Select xitem Group By xitem.Team Into First()) _
' Select RndList _
' Order By Rnd()
For Each item In lstCapitals
Randomize()
MsgBox(item.Team)
Next
End Sub

Your sample code doesn't explain how you choose the US State so I assume that you will have the value in a string somewhere. Here is a simple method you could use to generate a random string array to hold the values of the state capitals:
Dim sCorrectStateCapital As String = "Denver" ' This is hardcoded to "Denver" assuming that "Colorado" was the current US State you are playing the game for - you need to come up with your own logic to figure out how this works as I have no idea how you are choosing the State
Dim nButtonCount As Integer = 5 ' This is hardcoded to five since you have five buttons
Dim sCapitalsArray(nButtonCount - 1) As String ' Create the string array to hold the chosen capitals
' Loop five times and choose a different state capital each time
For i As Int32 = 0 To sCapitalsArray.Length - 1
Dim nTempIndex As Int32 = randomInt.Next(0, lstCapitals.Count - 1) ' Save the index value of the arraylist that we are choosing
sCapitalsArray(i) = lstCapitals.Item(nTempIndex) ' Populate the captials array
lstCapitals.RemoveAt(nTempIndex) ' Remove the selected capital from the list of possible choices since we do not want to choose it again
Next
' Test to see if the capitals array already contains the "correct" value
If Not sCapitalsArray.Contains(sCorrectStateCapital) Then
' The correct value is not already in the list so we overwrite one of the values in the array at a random index
sCapitalsArray(randomInt.Next(0, sCapitalsArray.Count - 1)) = sCorrectStateCapital
End If

The Form below has...
3 Labels: lblState, lblScore, lblAnswer
5 Buttons: btnCapital1, btnCapital2, btnCapital3, btnCapital4, btnCapital5
Public Class frmStateCapitalsQuiz
Public Class State
Public Name As String
Public Capital As String
Public Sub New(ByVal data As String)
Dim values() As String = data.Split(",")
Me.Name = values(0)
Me.Capital = values(1)
End Sub
Public Overrides Function ToString() As String
Return Me.Capital & ", " & Me.Name
End Function
End Class
Private R As New Random
Private Count As Integer
Private Correct As Integer
Private States As List(Of State)
Private CurrentState As State = Nothing
Private CurrentStateSet As List(Of State)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadStateData()
GenerateQuestion()
lblScore.Text = "Score: "
lblAnswer.Text = ""
End Sub
Private Sub LoadStateData()
States = New List(Of State)
Dim StateData As String = "Alabama,Montgomery;Alaska,Juneau;Arizona,Phoenix;Arkansas,Little Rock;California,Sacramento;Colorado,Denver;Connecticut,Hartford;Delaware,Dover;Florida,Tallahassee;Georgia,Atlanta;Hawaii,Honolulu;Idaho,Boise;Illinois,Springfield;Indiana,Indianapolis;Iowa,Des Moines;Kansas,Topeka;Kentucky,Frankfort;Louisiana,Baton Rouge;Maine,Augusta;Maryland,Annapolis;Massachusetts,Boston;Michigan,Lansing;Minnesota,St. Paul;Mississippi,Jackson;Missouri,Jefferson City;Montana,Helena;Nebraska,Lincoln;Nevada,Carson City;New Hampshire,Concord;New Jersey,Trenton;New Mexico,Santa Fe;New York,Albany;North Carolina,Raleigh;North Dakota,Bismarck;Ohio,Columbus;Oklahoma,Oklahoma City;Oregon,Salem;Pennsylvania,Harrisburg;Rhode Island,Providence;South Carolina,Columbia;South Dakota,Pierre;Tennessee,Nashville;Texas,Austin;Utah,Salt Lake City;Vermont,Montpelier;Virginia,Richmond;Washington,Olympia;West Virginia,Charleston;Wisconsin,Madison;Wyoming,Cheyenne"
For Each pair As String In StateData.Split(";")
States.Add(New State(pair))
Next
End Sub
Private Sub GenerateQuestion()
Dim shuffledStates = States.OrderBy(Function(x) R.NextDouble()).Take(5).ToList
CurrentState = shuffledStates(R.Next(shuffledStates.Count))
lblState.Text = CurrentState.Name
btnCapital1.Text = shuffledStates(0).Capital
btnCapital2.Text = shuffledStates(1).Capital
btnCapital3.Text = shuffledStates(2).Capital
btnCapital4.Text = shuffledStates(3).Capital
btnCapital5.Text = shuffledStates(4).Capital
End Sub
Private Sub btnCapitals_Click(sender As Object, e As EventArgs) Handles btnCapital1.Click, btnCapital2.Click, btnCapital3.Click, btnCapital4.Click, btnCapital5.Click
Dim SelectedCaptial As Button = DirectCast(sender, Button)
lblAnswer.Text = CurrentState.ToString
Count = Count + 1
If SelectedCaptial.Text = CurrentState.Capital Then
lblScore.BackColor = Color.Green
Correct = Correct + 1
Else
lblScore.BackColor = Color.Red
End If
Dim percentCorrect = CInt(CDbl(Correct) / CDbl(Count) * 100)
lblScore.Text = String.Format("Score: {0} / {1}, {2}% Correct", Correct, Count, percentCorrect)
GenerateQuestion()
End Sub
End Class

Related

How do I read and write this array of structure to/from a file?

I'm trying to write the array persons to a file and read it and have no clue on how to go about it. Here's my code:
Public Class Form1
Structure Person
Public name As String
Public height As Integer
Public weight As Double
End Structure
Dim persons(49) As Person
Dim arraySize As Integer = 0
Private Sub submitBtn_Click(sender As Object, e As EventArgs) Handles submitBtn.Click
If arraySize < 50 Then
Dim Name As String
Dim Height As Integer
Dim Weight As Double
Name = nameTxt.Text
Height = CInt(heightTxt.Text)
Weight = CDbl(weightTxt.Text)
nameTxt.Text = Nothing
heightTxt.Text = Nothing
weightTxt.Text = Nothing
arraySize += 1
persons(arraySize).name = Name
persons(arraySize).height = Height
persons(arraySize).weight = Weight
Else
MsgBox("The list of people is full now. You may no longer enter new people.")
End If
End Sub
Private Sub saveBtn_Click(sender As Object, e As EventArgs) Handles saveBtn.Click
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
End Sub
End Class
Any help on how to code this would be appreciated. Thank you!
I tried coding it to save the array persons (which is linked to the structure Person) to a file, but the app freezes, and i am not sure how to get around it.
try to use list :
Public Class Form1
<Serializable()> Structure Person
Public name As String
Public height As Integer
Public weight As Double
End Structure
dim persons As List(Of Person)
Private Sub submitBtn_Click(sender As Object, e As EventArgs) Handles submitBtn.Click
If persons.length < 50 Then
Dim Name As String
Dim Height As Integer
Dim Weight As Double
Name = nameTxt.Text
Height = CInt(heightTxt.Text)
Weight = CDbl(weightTxt.Text)
nameTxt.Text = Nothing
heightTxt.Text = Nothing
weightTxt.Text = Nothing
person.name = Name
person.height = Height
person.weight = Weight
persons.add(person)
Else
MsgBox("The list of people is full now. You may no longer enter new people.")
End If
End Sub
Private Sub saveBtn_Click(sender As Object, e As EventArgs) Handles saveBtn.Click
Using fs As New IO.FileStream("d:\backup\persons.dat", IO.FileMode.Create)
Dim formatter As New BinaryFormatter
formatter.Serialize(fs, persons)
End Using
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
Using fs As New IO.FileStream("d:\backup\persons.dat", IO.FileMode.Open)
Dim formatter As New BinaryFormatter
persons = DirectCast(formatter.Deserialize(fs), List(Of person))
End Using
End Sub
dont forget to add <Serializable()> in front of struc definition.

Auto fill Combo Boxs with data from SQL server database VB.Net

l have a data source that contains two columns
block_name total_lands
A-0 5
A-1 15
A-2 18
A-3 18
And I have two combo boxes one for the block name and the other for the no of lands
the first one is loaded with the block names
Private Sub LoadItems()
SQL.ExecQuery("SELECT block_name FROM blocks;")
For Each i As DataRow In SQL.DBDTable.Rows
ComboBox1.Items.Add(i("block_name"))
Next
End Sub
I want the second one to be loaded with numbers from 1 to whatever is in the data source row total_lands
For example if the user chose the block name as A-1 I want the second combo box to have the items from 1 to 15 add in it
My code trying to do so
Private Sub LoadNoOfLands()
SQL.AddParam("#blockname", ComboBox1.Text)
SQL.ExecQuery("SELECT totla_lands FROM blocks WHERE total_lands LIKE #blockname;")
For Each no As DataRow In SQL.DBDTable.Rows
Dim lands As Integer = no("block_lands")
'For Each i As Integer In lands
'
'
'Next
Next
End Sub
Load required data at once and use Enumerator.Range to generate collection of numbers for second combobox
Public Class Block
Public ReadOnly Property Name As String
Public ReadOnly Property TotalLands As Integer
Public ReadOnly Property Lands As Integer()
Public Sub New(name As String, totalLands As Intger)
Name = name
TotalLands = totalLands
Lands = Enumerable.Range(1, totalLands).ToArray()
End Sub
End Class
Private Function LoadBlocks() As Block()
Dim query = "SELECT block_name, total_lands FROM table"
Dim rows = SQL.ExecuteQuery(query)
Return rows.AsEnumerable().
Select(Function(row) New Block(row.Field(Of String)("block_name"), row.Field(Of Integer)("total_lands"))).
ToArray()
End Function
Private Sub SetupComboBox()
cmbBlocks.DisplayMemeber = "Name"
cmbBlocks.DataSource = LoadBlocks()
End Sub
Private Sub cmbBlocks_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cmbBlocks.SelectionChangeCommitted
Dim combobox As ComboBox = DirectCast(sender, ComboBox)
Dim block As Block = DirectCast(combobox.SelectedValue, Block)
cmbLands.DataSource = block.Lands
End
I have come up with a simple answer
Private Sub LoadNoOfLands()
cmbLands.Items.Clear()
SQL.AddParam("#blockname", cmbBlocks.Text)
SQL.ExecQuery("SELECT total_lands FROM blocks WHERE block_name LIKE #blockname;")
If SQL.HasException(True) Then Exit Sub
For Each i As DataRow In SQL.DBDTable.Rows
Dim lands = i("total_lands")
Dim r = 1
For r = 1 To lands
cmbLands.Items.Add(r).ToString()
Next
Next
End Sub
This function just adds number to combobox form 1 to the total_lands value
I created a class for the data.
Public Class Block
Public Property Name As String
Public Property TotalLands As Integer
Public Sub New(BlockName As String, Lands As Integer)
Name = BlockName
TotalLands = Lands
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
The combo box will call .ToString on the items to determine what to display.
We get the data from the database and add it to the List(Of Block)
Public Function FillBlocksList() As List(Of Block)
Dim lst As New List(Of Block)
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("Select block_name, total_lands From BlockTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
Do While reader.Read
Dim b As New Block(reader.GetString(0), reader.GetInt32(1))
lst.Add(b)
Loop
End Using
End Using
Return lst
End Function
To fill the first combo we get the list then loop through it adding the Block objects to the combo. You would probably call this from Form.Load.
Public Sub FillBlocksCombo()
Dim lst = FillBlocksList()
For Each item In lst
ComboBox1.Items.Add(item)
Next
End Sub
To fill the second combo cast the select item back its underlying type, Block and use the TotalLands property to add the numbers.
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim NumberOfLands = DirectCast(ComboBox1.SelectedItem, Block).TotalLands
For i = 1 To NumberOfLands
ComboBox2.Items.Add(i.ToString)
Next
End Sub

(VB.NET) display the lower half of a textfile to a listbox

I have to make a application that organizes a list of runners and their teams. In the following text file, I have to remove the top half of the text file (the top half being the listed teams) and display only the bottom half (the runners)in a listbox item.
The Text file:
# School [School Code|School Name|Coach F-Name|Coach L-Name|AD F-Name|AD L Name]
WSHS|Worcester South High School|Glenn|Clauss|Bret|Zane
WDHS|Worcester Dorehty High School|Ellsworth|Quackenbush|Bert|Coco
WBCHS|Worcester Burncoat High School|Gail|Cain|Kevin|Kane
QRHS|Quabbin Regional High School|Bob|Desilets|Seth|Desilets
GHS|Gardner High School|Jack|Smith|George|Fanning
NBHS|North Brookfield High School|Hughe|Fitch|Richard|Carey
WHS|Winchendon High School|Bill|Nice|Sam|Adams
AUBHS|Auburn High School|Katie|Right|Alice|Wonderland
OXHS|Oxford High School|Mary|Cousin|Frank|Daughter
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
101|WSHS|Sanora|Hibshman
102|WSHS|Bridgette|Moffitt
103|WSHS|Karine|Chunn
104|WSHS|Shanita|Wind
105|WSHS|Fernanda|Parsell
106|WSHS|Albertha|Baringer
107|WSHS|Carlee|Sowards
108|WDHS|Maisha|Kleis
109|WDHS|Lezlie|Berson
110|WDHS|Deane|Rocheleau
111|WDHS|Hang|Hodapp
112|WDHS|Zola|Dorrough
113|WDHS|Shalon|Mcmonigle
I have some code that reads each row from the text file as an array and uses boolean variables to determine where to end the text file. This worked with displaying only the teams, which I've managed to do. But I now need to do the opposite and display only the players, and I'm a bit stumped.
My Code:
Private Sub btnLoadTeams_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTeam.Click
' This routine loads the lstTeam box from an ASCII .txt file
' # School [School Code | Name | Coach F-Name| Coach L-Name | AD F-Name | AD L-Name]
Dim strRow As String
Dim bolFoundCode As Boolean = False
Dim bolEndCode As Boolean = False
Dim bolFoundDup As Boolean = False
Dim intPosition As Integer
Dim intPosition2 As Integer
Dim strTeamCodeIn As String
Dim textIn As New StreamReader( _
New FileStream(txtFilePath.Text, FileMode.OpenOrCreate, FileAccess.Read))
' Clear Team listbox
lstTeam.Items.Clear()
btnDeleteRunner.Enabled = True
Do While textIn.Peek <> -1 And Not bolEndCode
Me.Refresh()
strRow = textIn.ReadLine.Trim
If Not bolFoundCode Then
If "# SCHOOL " = UCase(Mid(strRow, 1, 9)) Then
bolFoundCode = True
End If
Else
If Mid(strRow, 1, 2) <> "# " Then
For Each item As String In lstTeam.Items
intPosition = InStr(1, strRow, "|")
strTeamCodeIn = Mid(strRow, 1, intPosition - 1)
intPosition2 = InStr(1, item, strTeamCodeIn)
If intPosition2 > 0 Then
bolFoundDup = True
MsgBox("Found Duplicate School Code: " & strTeamCodeIn)
End If
Else
bolEndCode = True
Next
If Not bolFoundDup Then
lstTeam.Items.Add(strRow)
Else
lstTeam.Items.Add("DUPLICATE School Code: " & strRow)
lstTeam.Items.Add("Please correct input file and reload teams")
bolEndCode = True
End If
End If
End If
Loop
End Sub
Ive put bolEndCode = True in between the part that reads the mid section of the text file, but all Ive managed to display is the following in the listbox:
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
Any help or hints on how I would display just the runners to my "lstPlayers" listbox would be greatly appreciated. I'm a beginner programmer and We've only just started learning about reading and writing arrays in my .NET class.
First I made 2 classes, one Runner and one School. These have the properties available in the text file. As part of the class I added a function that overrides .ToString. This is for he list boxes that call .ToString for display.
Next I made a function that reads all the data in the file. This is very simple with the File.ReadLines method.
Then I created 2 variables List(Of T) T stands for Type. Ours Types are Runner and School. I used List(Of T) instead of arrays because I don't have to worry about what the size of the list is. No ReDim Preserve, just keep adding items. The FillList method adds the data to the lists. First I had to find where the schools ended and the runners started. I used the Array.FindIndex method which is a bit different because the second parameter is a predicate. Check it out a bit. Now we know the indexes of the lines we want to use for each list and use a For...Next loop. In each loop an instance of the class is created and the properties set. Finally the new object is added to the the list.
Finally we fill the list boxes with a simple .AddRange and the lists.ToArray. Note that we are adding the entire object, properties and all. The neat thing is we can access the properties from the listbox items. Check out the SelectedIndexChanged event. You can do the same thing with the Runner list box.
Sorry, I couldn't just work with your code. I have all but forgotten the old vb6 methods. InStr, Mid etc. It is better when you can to use .net methods. It makes your code more portable when the boss says "Rewrite the whole application in C#"
Public Class Runner
Public Property BibNum As Integer
Public Property SchoolCode As String
Public Property FirstName As String
Public Property LastName As String
Public Overrides Function ToString() As String
'The listbox will call .ToString when we add a Runner object to determin what to display
Return $"{FirstName} {LastName}" 'or $"{LastName}, {FirstName}"
End Function
End Class
Public Class School
Public Property Code As String
Public Property Name As String
Public Property CoachFName As String
Public Property CoachLName As String
Public Property ADFName As String
Public Property ADLName As String
'The listbox will call .ToString when we add a School object to determin what to display
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Private Runners As New List(Of Runner)
Private Schools As New List(Of School)
Private Function ReadData(path As String) As String()
Dim lines = File.ReadLines(path).ToArray
Return lines
End Function
Private Sub FillLists(data As String())
Dim location = Array.FindIndex(data, AddressOf FindRosterLine)
'The first line is the title so we don't start at zero
For index = 1 To location - 1
Dim SplitData = data(index).Split("|"c)
Dim Schl As New School
Schl.Code = SplitData(0)
Schl.Name = SplitData(1)
Schl.CoachFName = SplitData(2)
Schl.CoachLName = SplitData(3)
Schl.ADFName = SplitData(4)
Schl.ADLName = SplitData(5)
Schools.Add(Schl)
Next
For index = location + 1 To data.GetUpperBound(0)
Dim SplitData = data(index).Split("|"c)
Dim Run As New Runner
Run.BibNum = CInt(SplitData(0))
Run.SchoolCode = SplitData(1)
Run.FirstName = SplitData(2)
Run.LastName = SplitData(3)
Runners.Add(Run)
Next
End Sub
Private Function FindRosterLine(s As String) As Boolean
If s.Trim.StartsWith("# Roster") Then
Return True
Else
Return False
End If
End Function
Private Sub FillListBoxes()
Dim arrRunners As Runner() = Runners.ToArray
Dim arrSchools As School() = Schools.ToArray
ListBox1.Items.AddRange(arrSchools)
ListBox2.Items.AddRange(arrRunners)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim arrRunner = ReadData("Runners.txt")
FillLists(arrRunner)
FillListBoxes()
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim Schl = DirectCast(ListBox1.SelectedItem, School)
TextBox1.Text = Schl.CoachLName
TextBox2.Text = Schl.Code
End Sub

Loading file into array then sorting from highest to lowest

I am trying to order the largest scores in a file that is loaded into an array. Currently, the program opens the file, then reads it and then splits up each line into two parts - a name and a score; then stores that in an array. I am not sure how I can sort the array to find the largest 10 scores and put that into a listbox. At the moment, the program finds any scores above 0 and puts it in the listbox
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, "GameResultsFile", OpenMode.Input)
For index = 0 To 99
Dim temp() As String = LineInput(FileNum).Split(",") 'CUTTING LINE INTO TWO SECTIONS
MemoryGame.HighScores(index).Name = temp(0) 'NAME (First Part of Line)
MemoryGame.HighScores(index).Score = temp(1) 'SCORE (Second Part of Line)
If temp(1) > 0 Then 'If any of the scores is above 0 then
ListBox1.Items.Add(temp(0) + " " + temp(1)) ' display the name of the person who got that score and their score
End If
Next
FileClose()
Comments and explainations in line
'Note Imports System.IO
Structure Player
Public Score As Integer
Public Name As String
'Added a constructor to the structure to make it easy to add new Player
Public Sub New(myScore As Integer, myName As String)
Score = myScore
Name = myName
End Sub
End Structure
Private HighScores(99) As Player
Private index As Integer 'used in both LoadArray and SortAndDisplayArray
Private Sub LoadArray()
Using sr As New StreamReader("GameResultsFile.txt")
Dim line As String
Do While sr.Peek() > -1 'Peek checks if there is another character in the file
line = sr.ReadLine()
Dim temp() As String = line.Split(","c) 'CUTTING LINE INTO TWO SECTIONS
'Notice the elements of the temp array are switched to match the
'Player constructor (Sub New)
HighScores(index) = New Player(CInt(temp(1)), temp(0))
index += 1 'not only keeps track of the index but remembers how many elements
'we have added to HighScores
Loop
End Using
End Sub
Private Sub SortAndDisplayArray()
'This is the LINQ way to do it, you can do a great deal in one line of code
'There is a loop underneath but you don't have to write it.
'I added a Take clause so we will not get a bunch of 0- in the list box going up to index 99
' You might want to show, for example only the top ten scorers, so change to Take 10
Dim orderArray = From scorer In HighScores Order By scorer.Score Descending Select $"{scorer.Score} - {scorer.Name}" Take index
ListBox1.DataSource = orderArray.ToList
End Sub
I still think a List(Of T) would be easier but I have a feeling your assignment requires you to use an array.
I'd do it something like this using IComparable
First I would load the data from your text file like so and save the data to a List Of and the Type would be the Player class down below.
'' Get Data From Text File And Create An Anonymous Type
Private Sub LoadPlayerAndScore(path As String)
'' Load data from text file
Dim data = From line In System.IO.File.ReadAllLines(path)
Let val = line.Split(",")
Select New With {Key .Name = val(0), Key .Score = val(1)}
'' Save data to list
For Each pair In data
Dim player As New Player With {
.Name = pair.Name,
.Score = pair.Score
}
playersList.Add(player)
Next
End Sub
I would then go on to create a player class which will Implement the ICompareble listed above.
Class Player
Implements IComparable(Of Player)
Public Property Name As String
Public Property Score As Integer
Public Sub Player(ByVal name As String, ByVal score As Integer)
Me.Name = name
Me.Score = score
End Sub
'' Sort Player From The Hightest Score To The Lowest Score
Private Function IComparable_CompareTo(other As Player) As Integer Implements IComparable(Of Player).CompareTo
Return other.Score.CompareTo(Me.Score)
End Function
End Class
I would then create some public variables such as
Dim playersList As New List(Of Player)
Dim fileLocation As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Settings.txt")
Change the path to your file's location.And finally in a Form Load Event I would call it all like this
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'' Load Data From Text File On Desktop
LoadPlayerAndScore(path:=fileLocation)
'' Sort List
playersList.Sort()
'' Add Values To List
For Each p As Player In playersList
ListBox1.Items.Add("Name: " + p.Name + " Score: " + p.Score.ToString())
Next
End Sub
Here is what the code should look something like altogether
Public Class Form1
Dim playersList As New List(Of Player)
Dim fileLocation As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Settings.txt")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'' Load Data From Text File On Desktop
LoadPlayerAndScore(path:=fileLocation)
'' Sort List
playersList.Sort()
'' Add Values To List
For Each p As Player In playersList
ListBox1.Items.Add("Name: " + p.Name + " Score: " + p.Score.ToString())
Next
End Sub
'' Get Data From Text File And Create An Anonymous Type
Private Sub LoadPlayerAndScore(path As String)
'' Load data from text file
Dim data = From line In System.IO.File.ReadAllLines(path)
Let val = line.Split(",")
Select New With {Key .Name = val(0), Key .Score = val(1)}
'' Save data to list
For Each pair In data
Dim player As New Player With {
.Name = pair.Name,
.Score = pair.Score
}
playersList.Add(player)
Next
End Sub
End Class
Class Player
Implements IComparable(Of Player)
Public Property Name As String
Public Property Score As Integer
Public Sub Player(ByVal name As String, ByVal score As Integer)
Me.Name = name
Me.Score = score
End Sub
'' Sort Player From The Hightest Score To The Lowest Score
Private Function IComparable_CompareTo(other As Player) As Integer Implements IComparable(Of Player).CompareTo
Return other.Score.CompareTo(Me.Score)
End Function
End Class
Here is the output I gotAnd here is what the text files data looked like.
ANDREW,25
MERVE,12
RUZGAR,50
And for the top ten people, follow the comments above.
How about try this?
Dim sortedArray = _
File _
.ReadAllLines("GameResultsFile") _
.Select(Function (line) line.Split(","c)) _
.Select(Function (parts) New With { .Name = parts(0), .Score = Integer.Parse(parts(1)) }) _
.OrderByDescending(Function (x) x.Score) _
.Select(Function (x) x.Name & " " & x.Score)
.ToArray()
For Each item As String In sortedArray
ListBox1.Items.Add(item)
Next

Loop till end of file VB.NET

I have a file containing the first name, second name and age of a person:
John, Smith, 35
Andrew, Jacobs, 52
I have split up the first name, second name and age and put them into arrays.
Becuase I know that there are 2 people (I set the array size to 1) , I am using the following 'for' loop:
For x = 0 to 1
textbox1.text = textbox1.text + first_name(x)
Next
I want to change this to the following:
For x = 0 to however long the file is
textbox1.text = textbox1.text + first_name(x)
Next
However, when I try to use 0 to first_name.length it doesn't work.
If what you want to do is put the contents of a line-delimited file into a VB string array, why don't you just let the file tell you how many lines there are?
Like:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim listOfPeople As String()
listOfPeople = System.IO.File.ReadAllLines("C:\\Temp\\file.txt")
For i As Integer = 0 To listOfPeople.Length - 1
Console.WriteLine(listOfPeople(i))
Dim person As String = listOfPeople(i)
Dim personAttributes As String() = person.Split(",")
For j As Integer = 0 To personAttributes.Length - 1
' do something with the attribute
Next
Next
End Sub
How about creating a Person class - then you won't have separate arrays to carry around.
Try this:
Public Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
End Class
Public Function ReadPeople(filePath As String) As Person()
Return (From record In IO.File.ReadAllLines(filePath)
Let Terms = record.Split(","c)
Select New Person With {.LastName = Terms(0), .FirstName = Terms(1), .Age = CInt(Terms(2))}) _
.ToArray
End Function
Usage:
Dim people = ReadPeople("c:\people.txt")
If I were you I would just make things simple as possible.
Try this:
textbox1.Text = _
String.Join("", File.ReadAllLines("") _
.Select(Function(x) x.Split(","C)(0).Trim()))

Resources