I’m writing an app in C#/.NET 4.5 and I have a dictionary defined like this:
Dictionary<int, string> d = new Dictionary<int, string>();
My integer keys are sequential and unique and, except for empty strings, my values will be unique as well. For example:
Key Value
0 AAAAAAAAAA
1 BBBBBB
2 (empty string)
3 CCCCCCCCCCCCCCCCCCCCCCCC
4 DDDDDDDDDDDDDDD
5 EEEEEEEEEEEEEEEEEEE
6 (empty string)
When I have a new string to add to the dictionary, I need to assign it to one of the keys which has a value of (empty string). Ideally, I’d like to do this at the first instance of such a key. I’m currently looping through my dictionary like this:
int keyNumber;
foreach (KeyValuePair<int, string> pair in d)
{
if (pair.Value == string.Empty)
{
keyNumber = pair.Key;
break;
}
}
d[keyNumber] = "new string goes here!";
This works but is there a better (or faster) way to accomplish the same thing? If this actually is the best approach, is it possible to shorten it into a LINQ expression?
EDIT —————————————————————————–
I left out what was probably something important to explain. The values that get loaded into my dictionary are actually loaded from a binary file comprised of fixed-length byte arrays which hold ASCII strings. The file will always consist of 5000000 bytes or 100000 total strings @ 50 bytes each. The file structure was determined by some hardware limitations on the device that will consume the file. So the key for each KeyValuePair in my dictionary is actually used to determine the offset into the file where I need to write any changes when the user is finished making them. For example, using a a key of 4, I then multiply by 50 to a starting offset of 200 bytes. Then I write the modified string back at that location. Sorry for omitting that in my original post.
However, a dictionary is really meant to store true key-value pairs. A list sounds like it is better suited to your case where it seems like you only really need to store values. Even so, list elements are still accessible by index and you can include empty elements so there doesn’t (from what you have stated) seem to be a reason to stick with a dictionary.