I am using a foreach loop and Directory.GetFiles() to collect some information about the files in a directory. I want to store 3 strings: Filename, FilePath, DirectoryName. I can get this information okay, but I’m wondering what the best way to store the data is.
I want to be able to look up one of strings, and easily find the others. For example, if they are in 3 arrays, I could use a forloop to scan Filename array and find that the entry that I want is at index 45. I can then just use FilePath[45], DirectoryName[45] to get the entries in the other two arrays.
Would this be the most efficient to store these strings? And if so, assuming that in another case, I wasn’t able to get the size of the arrays with the GetFiles() method beforehand, would a List be the suitable alternative?
If you’ve got three associated values, encapsulate them in a type. It needn’t be a particularly complicated type, although I’d probably make it immutable – just three properties initialized from a constructor. The trickiest bit is naming it, given that
FileInfois already part ofSystem.IO… But suppose you settled on the (sucky) name ofFileData:This won’t be quite as efficient (in terms of memory) as three separate arrays, but it would be a darned sight more practical to use, particularly with LINQ. Spend the time that you gain from not dealing with the separate arrays on optimizing bits which really matter. The memory taken by the strings is likely to dwarf the overhead of the container object.
You could make this a struct instead of a class, which would be slightly more efficient in some ways and slightly less efficient in others. I usually use a class unless I’ve got a good reason not to.
And yes, I would usually use a
Listrather than an array – Eric Lippert has some good reasons why…One thing that bothers me slightly: are these three pieces of information genuinely orthogonal, or could you construct the full path from the directory name and file name? If so, you should probably only store the first two, and construct the third when you need to.