I have a directory in which filenames are entirely numbers. I want to find the highest valued number so that I can open that file and begin processing the data in the file. What would be the easiest way to go about this? My first blush idea is to load the directory of filenames into an array and iterate through the array looking to see which one is the largest. Suggestions?
He does not _need_ to allocate an array...
Moron
2010-02-24 18:39:13
allocating an array is very cheap in comparison to filesystem traversal.
Vlad
2010-02-24 19:08:44
I had a friend who told me this story: They had a product which had a database backend, and the main thing the code did was to generate queries to the backend. On a perf measurement, it turned out that this query generation was far slower than the actual DB calls, which was not obvious looking at the code! In any case, i just pointed it out as something that can be avoided... so why not?
Moron
2010-02-25 00:01:11
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" (c)
Vlad
2010-02-25 09:42:44
I wasn't looking at it in a resource cost manner, more of in an elegance manner. Traversing an array to find the highest numbered filename seemed ugly and manual.
Xir
2010-02-25 13:44:15
A:
You can just use DirectoryInfo.GetFiles, and use LINQ to find the highest value number:
string filename = myDirectoryInfo.GetFiles().Select(fileInfo => int.Parse(fileInfo.Name)).Max().ToString();
(However, you probably would want some more rigorous error checking, since this will throw if the folder contains a filename that isn't just a number...)
Reed Copsey
2010-02-24 18:38:52
what do you think finding max in array using BinarySearch isn't fast?
Professional2Hire
2010-02-24 18:43:06
@Professional2Hire: Hrm? This should perform fine - finding the filenames from disk is going to be a lot slower than finding the max... This is just a nice, clean one-liner.
Reed Copsey
2010-02-24 18:47:17
Binary search won't work anyway, since the numbers aren't guaranteed to be sorted.
David
2010-02-24 19:13:03
I have little experience with LINQ, but I'll be trying this solution out later to see how it works. Thanks!
Xir
2010-02-25 13:44:59
A:
Yes, you can do this and the easiest way to load the all the filenames at once is in Directory Class
use GetFiles function.
Thanks
Professional2Hire
2010-02-24 18:41:54
Then for each filename in the resultant array, pass Path.GetFileNameWithoutExtension(filename) to Int32.TryParse(). If it succeeds, compare Path.GetFileNameWithoutExtension(filename).ToString() to the current maximum.
JeffH
2010-02-24 18:51:08
+2
A:
Would TryParse help here?
Int64 val;
string maxFileName = dirInfo.GetFiles().OrderByDescending(s => Int64.TryParse(s.Name, out val) ? val : 0).First().Name;
masenkablast
2010-02-24 18:54:34