Reputation: 31
For this part of my assignment I need to do the following:
Create a function that returns a sorted list of string type keys and integer type values. Inside the function, declare a new sorted list that has the same structure as the function’s return type. Then, using a nested for loop for populating the sorted list, go through the product list and year list such that the product and year is concatenated together to create a key, and the corresponding demand value from the demand table array is retrieved as the value for this key to be entered to the sorted list.
I've written the following code to do that, however it throws "'System.ArgumentException' in System.dll" after 1 iteration. The test MessageBox will only display "ModelX 2013 205" and then the error will be thrown.
Public Function GetProductDemand() As SortedList(Of String, Integer)
Dim prodDemand As New SortedList(Of String, Integer)
Dim count As Integer = 0
For Each product In products
For Each yr In years
Dim key As String
key = product & " " & yr
For i As Integer = 0 To 4
prodDemand.Add(key, demand(count, i)) 'stops here after 1 iteration
MessageBox.Show(key & " " & prodDemand(key)) 'test to display results
Next
Next
count += 1
Next
Return prodDemand
End Function
Any reason why this is happening? Here's the rest of the relevant code:
Dim products As List(Of String)
Dim years As List(Of String)
Dim demandList As SortedList(Of String, Integer)
Dim demand As Integer(,)
Private Sub frmDemand_Load(sender As Object, e As EventArgs) Handles MyBase.Load
products = GetProducts()
years = GetYears()
demand = GetDemand()
demandList = GetProductDemand()
End Sub
Private Function GetDemand() As Integer(,)
Return {
{205, 220, 245, 230},
{160, 174, 152, 144},
{480, 424, 396, 456}
}
End Function
Public Function GetProducts() As List(Of String)
Dim prods As New List(Of String)
prods.Add("ModelX")
prods.Add("ModelY")
prods.Add("ModelZ")
Return prods
End Function
Public Function GetYears() As List(Of String)
Dim yr As New List(Of String)
yr.Add("2013")
yr.Add("2014")
yr.Add("2015")
yr.Add("2016")
Return yr
End Function
Upvotes: 0
Views: 139
Reputation: 107536
I read the problem statement closer. I don't think you need the inner-most for loop. The answer here is to base the indices off of the lists:
Public Function GetProductDemand() As SortedList(Of String, Integer)
Dim prodDemand As New SortedList(Of String, Integer)
For i = 0 To products.Length - 1
For j As Integer = 0 To years.Length - 1
Dim key As String = String.Format("{0} {1}", products(i), years(j))
prodDemand.Add(key, demand(i, j))
MessageBox.Show(key & " " & prodDemand(key)) 'test to display results
Next
Next
Return prodDemand
End Function
Upvotes: 1