Skip to content

Instantly share code, notes, and snippets.

@ddikman
Last active September 5, 2016 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddikman/5e3ca0e5278a06ae7d8ee9d41d25ea4a to your computer and use it in GitHub Desktop.
Save ddikman/5e3ca0e5278a06ae7d8ee9d41d25ea4a to your computer and use it in GitHub Desktop.
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;
}
}
@ddikman
Copy link
Author

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