Skip to content

Instantly share code, notes, and snippets.

@vabka
Last active October 9, 2021 02:56
Show Gist options
  • Save vabka/c675c5b7e3b4020ed1bebaaa6cf3235e to your computer and use it in GitHub Desktop.
Save vabka/c675c5b7e3b4020ed1bebaaa6cf3235e to your computer and use it in GitHub Desktop.
// And same for IQueryable
public static class EnumerableExtensions
{
public static T? SingleOrNull<T>(this IEnumerable<T> seq, Func<T, bool> predicate) where T : struct
{
var data = seq.Where(predicate).Take(2).ToArray();
if (data.Length == 2)
throw new InvalidOperationException();
if (data.Length == 0)
return null;
return data[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment