Last active
September 5, 2016 08:08
-
-
Save ddikman/5e3ca0e5278a06ae7d8ee9d41d25ea4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.