Nice:
if (folderPaths.Any(path => !Directory.Exists(path))) throw new DirectoryNotFoundException();
Nicer:
string pathNotFound; if (folderPaths.Any(path => !Directory.Exists(path), out pathNotFound)) throw new DirectoryNotFoundException("Could not find path: " + pathNotFound);
The implementation of
public static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate, out T found)
left as a trivial exercise to the reader.
Seems like you and I had a conversation about something like this once. IIRC it ended with code that looked like:
string pathNotFound = folderPaths.FirstOrDefault(path => !Directory.Exists(path));
if (pathNotFound != null)
throw new DirectoryNotFoundException(“Could not find path: ” + pathNotFound);
Comment by Todd — June 18, 2008 @ 9:36 pm
Is there a reason not to simply use FirstOrDefault here? Do we consider it possible that folderPaths contains a null value?
Comment by Dave — June 19, 2008 @ 6:43 am
FirstOrDefaultis certainly an option. But callingDirectory.Existswithnullreturns false. So this is a case where anullreturn value would be ambiguous.I do want to contend, though, that “if (…Any(…))” communicates the intent of the code more clearly than attempting to find a value and then checking if it is set.
Comment by Jacob — June 19, 2008 @ 7:11 am