Reputation: 3
I have a 2 dimensional array that contains multiple strings. It looks something like this;
[1] [2] [3]
[1] [4] [5]
[7] [9] [8]
I need a piece of code that returns the index of all positions [1] occurs within the array.
Upvotes: 0
Views: 6069
Reputation: 550
This an improved answer of tinstaafl's code
Sub CountryCode(ByVal searchterm As String)
Dim data As New List(Of List(Of String))(
{
{"AF", "Afghanistan"}.ToList,
{"AL", "Albania"}.ToList,
{"DZ", "Algeria"}.ToList,
{"AS", "American Samoa"}.ToList,
{"AD", "Andorra"}.ToList,
{"AO", "Angola"}.ToList,
{"AI", "Anguilla"}.ToList,
{"AQ", "Antarctica"}.ToList,
{"AG", "Antigua And Barbuda"}.ToList,
{"AR", "Argentina"}.ToList,
{"AM", "Armenia"}.ToList,
{"AW", "Aruba"}.ToList,
{"AU", "Australia"}.ToList,
{"AT", "Austria"}.ToList,
{"AZ", "Azerbaijan"}.ToList
})
Dim coords As New List(Of Tuple(Of Integer, Integer))
For Row As Integer = 0 To data.Count - 1
Dim found As Integer = data(Row).IndexOf(searchterm)
If found >= 0 Then
Debug.Print(Row, found)
coords.Add(New Tuple(Of Integer, Integer)(Row, found))
'Based on the index number of the item and the second piece will be displayed
'{"AF", "Afghanistan"}.ToList, 'index: 1 "AF" is item 1 and "Afghanistan" is item 2
'{"AL", "Albania"}.ToList, 'index: 2 "AL" is item 1 and "Albania" is item 2
'{"DZ", "Algeria"}.ToList, 'index: 3
'{"AS", "American Samoa"}.ToList, 'index: 4
'{"AD", "Andorra"}.ToList, 'index: 5
Debug.Print(data(Row).Item(1).ToString) 'prints anything in the right column... searchterm = "AT" would print "Austria"
End If
Next
End Sub
Upvotes: 1
Reputation: 6948
If your data contains a lot of elements you might not want to iterate through every element. Using a List(Of List(Of String)) would allow you to only loop through the outer list and just check the inner lists. something like this:+
Dim data As New List(Of List(Of String))(
{
{"[1]", "[2]", "[3]"}.ToList,
{"[1]", "[4]", "[5]"}.ToList,
{"[7]", "[9]", "[8]"}.ToList
})
Dim searchterm As String = "[1]"
Dim coords As New List(Of Tuple(Of Integer, Integer))
For Row As Integer = 0 To data.Count - 1
Dim found As Integer = data(Row).IndexOf(searchterm)
If found >= 0 Then
coords.Add(New Tuple(Of Integer, Integer)(Row, found))
End If
Next
Upvotes: 0
Reputation: 26424
Here is a code sample for you:
Dim a(,) As String = {{"[1]", "[2]", "[3]"},
{"[1]", "[4]", "[5]"},
{"[7]", "[9]", "[8]"}}
Dim indexList As New List(Of Tuple(Of Integer, Integer))
For iRow As Integer = 0 To UBound(a, 1)
For jCol As Integer = 0 To UBound(a, 2)
If a(iRow, jCol) = "[1]" Then 'save i and j somewhere
indexList.Add(New Tuple(Of Integer, Integer)(iRow, jCol))
End If
Next
Next
At the end of execution, indexList
has two values, (0,0)
and (1,0)
, where the first index is a row, and the second is a column. You may want to change this to use your custom structure instead of a Tuple
. Generics are kind of hard to debug in the long run, because of weird names showing up in debugger.
Upvotes: 0