Jacob Carpenter’s Weblog

June 18, 2008

.Any overload

Filed under: Uncategorized — Jacob @ 4:12 pm


if (folderPaths.Any(path => !Directory.Exists(path)))
    throw new DirectoryNotFoundException();


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.



  1. 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

  2. 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

  3. FirstOrDefault is certainly an option. But calling Directory.Exists with null returns false. So this is a case where a null return 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

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: