//Declaration
Dim values As New List(Of Dictionary(Of String, String))()
I am trying to create a multidimensional array.
this is my code:
con.Open()
ccsfreader = ccsfcomm.ExecuteReader
ccsfreader.Read()
If ccsfreader.HasRows Then
Do
values.Add(New Dictionary(Of String, String)() From {{"CostCentre", ccsfreader.Item("CostCentre")}})
values.Add(New Dictionary(Of String, String)() From {{"ProcessDescription", ccsfreader.Item("ProcessDescription")}})
Loop While ccsfreader.Read()
End If
con.Close()
For Each value As Dictionary(Of String, String) In values
Dim CostCentre As String = value("CostCentre")
Dim ProcessDescription As String = value("ProcessDescription")
cmblaborcost.Items.Add(CostCentre)
Next
My error is:
The given key was not present in the dictionary.
i want an output like this:
1 => array(
CostCentre=>10.00
ProcessDescription=>"up"
)
2 => array(
CostCentre=>20.00
ProcessDescription=>"sided"
)
3 => array(
CostCentre=>110.00
ProcessDescription=>"cutted"
)
You have two dictionaries in the list. One of which contains only "CostCentre" key, and the other contains only "ProcessDescription" key. So when you try to access both keys from a dictionary, one key must be missing.
You may want to use List(Of Tuple(Of String, String)) instead of List(Of Dictionary(Of String, String)). This example works for me :
Dim values As New List(Of Tuple(Of String, String))
values.Add(Tuple.Create("a1", "a2"))
values.Add(Tuple.Create("b1", "b2"))
values.Add(Tuple.Create("c1", "c2"))
'generate array from List of Tuple'
Dim result = values.Select(Function(x) New String() {x.Item1, x.Item2}).ToArray()
For Each s As String() In result
Console.WriteLine(s(0) & ", " & s(1))
Next
And for your case, it could be something like this :
'example to add item to list'
Dim values As New List(Of Tuple(Of String, String))
......
If ccsfreader.HasRows Then
Do
'values.Add(Tuple.Create(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription"))'
values.Add(New Tuple(Of String, String)(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription")))
Loop While ccsfreader.Read()
End If
.......
'example to access item from list'
For Each value As Tuple(Of String, String) In values
Dim CostCentre As String = value.Item1
Dim ProcessDescription As String = value.Item2
cmblaborcost.Items.Add(CostCentre)
Next
Related
I have the following JSON.
[["NAME","S0101_C01_008EA","S0101_C01_031M","state","county"],
["Alcona County, Michigan",null,"1.1","26","001"],
["Alger County, Michigan",null,"1.7","26","003"],
["Allegan County, Michigan",null,"0.2","26","005"],
["Alpena County, Michigan",null,"0.9","26","007"],
["Antrim County, Michigan",null,"0.9","26","009"],
["Arenac County, Michigan",null,"0.8","26","011"]]
I'm trying to deserialize it into an array of objects. I'm not sure why I'm having such a hard time.
I can get the info I need using .
Dim PopulationByState As List(Of JArray) = JsonConvert.DeserializeObject(Of List(Of JArray))(response)
Dim lst As New List(Of String) 'create a new list to hold the strings
For Each t As JToken In PopulationByState
For Each i In t.Children()
ListBox1.Items.Add(i)
Next
Next
You may deserialize it to a List(Of List(Of Object)):
Dim PopulationByState As List(Of List(Of Object)) = _
JsonConvert.DeserializeObject(Of List(Of List(Of Object)))(response)
Dim state As List(Of Object)
For Each state In PopulationByState.Skip(1) ' .Skip(1) to skip the header '
ListBox1.Items.Add(String.Join(vbTab, state))
Next
Demo (with output to console instead of filling a list box): https://dotnetfiddle.net/XQ3w2Z
I am writing a function that will allow me to input some values and then this will return this as a list. This is my code currently.
Structure question
Dim asking As String
Dim answers As List(Of String)
End Structure
Private Function addQuestionToList(toAsk As String, answers() As String) As question
addQuestionToList.asking = toAsk
Dim listTemp As List(Of String)
For i As Integer = 0 To answers.Count - 1
listTemp.Add(answers(i))
Next
addQuestionToList.answers = listTemp
End Function
#Region "Quiz Questions"
Dim GTAQuestions As List(Of question)
Sub initializeGTAQuestions()
GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"}))
End Sub
#End Region
Change your code:
Dim GTAQuestions As List(Of question)
Sub initializeGTAQuestions()
GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"}))
End Sub
with this:
Dim GTAQuestions As New List(Of question)
Sub initializeGTAQuestions()
GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"}))
End Sub
You need to initialize each instance of the structure. One option is to include a custom new method in your structure, so your structure and function will look like this:
Structure question
Dim asking as String
Dim answers as List(Of String)
Public Sub New (ByVal _asking as String, ByVal _answers as List(Of String))
asking = _asking
answers = _answers
End Sub
End Structure
Private Function addQuestionToList(ByVal asking as String, ByVal answers() as String) as question
Dim lstAnswers as New List(Of String)
For Each answer As String in answers
lstAnswers.Add(answer)
Next
Return New question(asking, lstAnswers)
End Function
I have a problem in my code. here is the problematic snippet. The reading of the line does work, but at the point where he should fill the zeilendict with the keys and the values, he throws an "System.NullReferenceException" and I dont know why.
Did I do something wrong in the loop, or is the dictionary not right iniziated? or is arr1 empty?
Module Module1
Public zeilendict As Dictionary(Of String, Integer)
Public insertdict As Dictionary(Of String, String)
Public Sub einlesen()
Form1.ID = 0
Form1.OpenFileDialog1.ShowDialog()
Form1.path = Form1.OpenFileDialog1.FileName
Form1.OpenFileDialog1.Dispose()
Dim fs As FileStream = New FileStream(Form1.path, FileMode.Open, FileAccess.Read)
Dim sr As StreamReader = New StreamReader(fs)
Dim ersteZeile = sr.ReadLine()
Form1.arr1 = ersteZeile.Split(New Char() {";"c})
sr.Close()
fs.Close()
Dim i As Integer
For i = 0 To Form1.arr1.Length - 1
Form1.DataGridView1.Rows.Add(Form1.arr1(i))
Next
Dim i1 As Integer
For i1 = 0 To Form1.arr1.Length - 1
zeilendict.Add(Form1.arr1(i1), 0)
Next
It seems you have not initiated your dictionary. There for adding items will give a NullRefException
Try adding:
Public zeilendict As Dictionary(Of String, Integer) = new Dictionary(Of String, Integer)()
or set this as first line in your method:
zeilendict = new Dictionary(Of String, Integer)()
Also do this for the other Dictionary
Add the keyword "New" to your declartion to initialize your dictionary:
Public zeilendict As New Dictionary(Of String, Integer)
Otherwise it will only be declared but contain nothing, therefore the Exception when you try to add something.
More information: http://msdn.microsoft.com/en-us/library/7zc73115%28v=vs.90%29.aspx
I have a text file like:
[edit] the number of line is unknown, it could be hundreds of lines.
How would I store them in a multidimensional array? I want my array to look like:
sample(0)(0) = "--------"
sample(0)(1) = "Line1"
..and so on
sample(1)(0) = "--------"
sample(1)(3) = "Sample 123"
..and so on
What I have done so far was to open the file and store in a 1-dimentional array:
logs = File.ReadAllLines("D:\LOGS.TXT")
I have tried creating an Array of string like:
Dim stringArray as String()()
stringArray = New String(varNumber0)(varNumber1)
But it returns and error.
You can use File.ReadLines/File.ReadAllLines to get the lines and a simple For Each-loop to fill a List(Of List(Of String)). Then you can use
list.Select(Function(l) l.ToArray()).ToArray()
to get the String()() (jagged array):
Dim lines = File.ReadLines("D:\LOGS.TXT")
Dim list As New List(Of List(Of String))
Dim current As List(Of String)
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
list.Add(current)
Else
current.Add(line)
End If
Next
Dim last = list.LastOrDefault()
If last IsNot Nothing Then
If Not current Is last AndAlso current.Any() Then
list.Add(current)
ElseIf Not last.Any() Then
list.Remove(last) ' last line was ("----------")'
End If
End If
Dim stringArray As String()() = list.Select(Function(l) l.ToArray()).ToArray()
If you want to include the --------- in the array at the first position:
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
current.Add(line)
list.Add(current)
Else
current.Add(line)
End If
Next
Try like this but you need to customize according to you
Dim mArray(10,10) As String
Dim i As Integer = 0
For I=0 to 10
For J=0 to 10
For Each line As String In System.IO.File.ReadAllLines("file.txt")
mArray(i,j) = cmdReader.Item(line)
Next
Next
Next
Use declaration like this (this is just a generic)
Dim dim1 As Integer = 0
Dim dim2 As Integer = 0
Dim strings(,) As String
Do
dim1 = NewDimensionNumberFromFile
dim2 = NewSecondDimensionNumberFromFile
ReDim Preserve strings(dim1, dim2)
strings(dim1, dim2) = ValueFromfile
Loop While (Not EOF()) 'this will determine
Dim SteamGames As New Dictionary(Of String, String)
For Each Game As String In System.IO.Directory.GetDirectories(Me.tb_SteamDir.Text)
SteamGames.Add(Game, System.IO.Path.GetFileName(Game))
Next Game
For Each Pair As KeyValuePair(Of String, String) In SteamGames
dgv_Table.Rows.Add(Pair.Key)
dgv_Table.Rows.Add(Pair.Value)
Next Pair
I am getting both the folder directory and the folder's name in the same column, how do I make them separate into different columns?
This should load the ComboBox and the DataGridView as you requested:
Dim DT As New DataTable
DT.Columns.Add("Full Path")
Dim GameNames_Master As New List(Of String)
For Each Dir As DirectoryInfo In New DirectoryInfo(Me.tb_SteamDir.Text).GetDirectories
GameNames_Master.Add(Dir.Name)
DT.Rows.Add(New Object() {Dir.FullName})
Next Dir
dgv_Table.DataSource = DT
Me.cb_Games.DataSource = GameNames_Master