I've been working on a project, where I need something like a Dictionary
, but at the same time also a List(Of KeyValuePair(Of String, String))
. I have two questions, one on which type to use and how to preform the tasks I need, two to get confirmation on the possibility of another requirement.
The project is based on RS232 communication, and I have all the serial port stuff sorted. I have a group of units, split into two types, that get placed in a random order. I need to find the units that are on and sort the order they're in. I have a list of addresses to the units that I need to communicate with, the addresses are stored as hexadecimal strings. For each address I have a status bit which is also stored as a string, as a 1 or 0.
I need to be able to iterate through my list of unit arrays (which are read in numerical order of the addresses from a text file) and sort them based on the order the units are physically in real life (in another List/Dictionary)
I need to be able to manipulate the List or Dictionary in a few ways.
- Firstly, I need to be able to add and remove entries (which both can do)
- Secondly, I need to be able to access the index of a desired key.
- Thirdly, I need to be able to iterate through all the entries in a
For Each
loop.
The problems I've found is that with the Dictionary, they're unsorted so I can't find the index of a specific Key, and I've been getting the same problem with the List(Of KeyValuePair...
where I try and Add to and Remove from the two arrays, but I can't get the index to extract the value of the state bit in the unsorted string.
The second question is about the fact I want to (in the next step) have a data type that has the above list/dictionary as well as an array of strings that represents a list of sensors on that unit and their states.
Thanks for any help!
Edit: The suggested duplicate gives answers for indexing by the key. However I need the integer index of the Dictionary or List to store in a separate variable. This is required to ensure the reply is the same address as the one asked for (as it broadcasts to all units). A bit more clarification of what I'm iterating over: I'm iterating over the decreasing array, as I need to check every unit still in that array for their status, and am removing the one that's just been added to the sorted array.
Edit 2: I have found a current workaround to the problem. I use a dictionary, and make an ICollection of it's keys and iterate through that. I'm now wondering whether having a sorted "list" in a regular dictionary is bad practice or not. I only need it to look up relative to the keys, but it is important that it is always in the same order. Should I then change it to a sorted list or will it always appear in the same order?