Created
January 9, 2025 18:12
-
-
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.
This file contains hidden or 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 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