Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
public static class EnumerableExtensions
public static bool TryGetFirst<T>(this IEnumerable<T> source, Func<T, bool> predicate, out T result)
result = source.FirstOrDefault(predicate);
if (default(T) == null)
return result != null;
return default(T).Equals(result);
public static bool TryGetSingle<T>(this IEnumerable<T> source, Func<T, bool> predicate, out T result)
var results = source.Where(predicate).ToArray();
if (results.Length > 1)
throw new InvalidOperationException($"Collection contains more than a single {typeof(T).Name} matching predicate.");
if (results.Length == 0)
result = default(T);
return false;
result = results[0];
return true;
Copy link

ddikman commented Sep 2, 2016

Just a small snippet for two functions I find myself using quite often, the TryGetFirst because the Try-pattern is nicer sometimes than the if(result != null) pattern.

The TryGetSingle is mostly due to the fact that the Single() enumerable extension throws (or at least used to throw) the same message for when there were no items in the list and when there were more than 1. I usually find that if there's more then one, then there's an error and if there isn't one I want to handle that in a different way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment