String pairs (multidimensional array?) C#
I basically want to keep a tra开发者_如何学Gock of old filenames and each file's new filename.
I could use a Dictionary I suppose, but I want to keep it really lightweight.
Would a multidimensional string array work just as well?
Use the Dictionary<string,string>
class:
- It manages its own size for you
- It uses hashes to speed up searching for elements
- You can just go
fileNames[oldName]
to get the name instead of using a loop or LINQ
Really, the Dictionary is the lightweight solution here.
The problem with using Dictionary<string,string>
in your scenario is that all keys need to be unique, so if you are using 'old file name' as a key, then you cannot have 2 scenarios where the 'old file name' was the same.
The best solution (in my opinion) is
List<Tuple<string,string>>
which will also be ordered with the lastest added last etc.
a new entry would look like
List<Tuple<string,string>> list = new List<Tuple<string, string>>();
list.Add(Tuple.Create(oldfilename,newfilename));
and then to find all new files for a particular old file name you could do the following:
var files = list.Where(t => t.Item1 == oldfilename);
You could also consider using StringDictionary, but its kinda old!
It was used in the land before generics, when dinosaurs ruled the earth.
What's your definition of lightweight? Are you worried about memory use or runtime?
With a multidimensional string array, you'd have to search through the array yourself (you could sort the array and do a binary search, but that's still not as nice as a hash table in the general case), so you would lose out on runtime cost on access.
With a multidimensional string array, you also need to know in advance how many entries you're going to need, to allocate memory. If you don't, you lose time and churn memory reallocating ever-larger arrays. A Dictionary doesn't use contiguous regions of memory, so it doesn't reallocate on expansion.
Finally, on the memory front, keep in mind that a string is a reference. The difference in memory use you'll see will only be related to the lookup structure, which is probably small compared to the data you want to keep track of. If the concern is to keep contiguous blocks of memory for cache efficiency, here neither solution is better than the other, as the strings are stored outside of the datastructure (being references), so any string reads lose that contiguity.
So to conclude, there's really no reason to use a multidimensional array over a dictionary.
精彩评论