Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Created January 9, 2025 18:12
Show Gist options
  • Save peteraritchie/a2d932a7ea1b15c20cb0464dba66477e to your computer and use it in GitHub Desktop.
Save peteraritchie/a2d932a7ea1b15c20cb0464dba66477e to your computer and use it in GitHub Desktop.
An extension method that uses the Try pattern to get a single value from a collection.
public static class Extensions
{
/// <summary>
/// Try to get the single value from the collection
/// </summary>
/// <typeparam name="T">The type of elements in the collection</typeparam>
/// <param name="source">the source collection</param>
/// <param name="predicate">The predicate to test elements</param>
/// <param name="item">The item found, or null</param>
/// <returns>true if found, false otherwise</returns>
public static bool TrySingle<T>(this IEnumerable<T> source, Func<T, bool> predicate, out T? item)
{
item = source.SingleOrDefault(predicate);
return item != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment