tags:

views:

59

answers:

4

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?

A: 

What is bad in your "blush idea"? I see no problems with it.

Vlad
He does not _need_ to allocate an array...
Moron
allocating an array is very cheap in comparison to filesystem traversal.
Vlad
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
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" (c)
Vlad
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
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
what do you think finding max in array using BinarySearch isn't fast?
Professional2Hire
@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
Agreed as I am not much fimiliar with linq
Professional2Hire
Binary search won't work anyway, since the numbers aren't guaranteed to be sorted.
David
I have little experience with LINQ, but I'll be trying this solution out later to see how it works. Thanks!
Xir
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
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
+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
This looks like it will work nicely! Thank you!
Xir