/// <summary>
/// Tries to get the first item that meets a condition from a collection.
/// </summary>
/// <typeparam name="T">Type of items in the collection</typeparam>
/// <param name="source">Collection to get the first item of</param>
/// <param name="predicate">Method that returns <see langword="true"/> if a given item meets the condition</param>
/// <param name="item">Found item</param>
/// <returns><see langword="true"/> if an item was found</returns>
public static bool TryGetFirst<T>(this IEnumerable<T> source, Predicate<T> predicate, [MaybeNullWhen(false)] out T item)
{
ArgumentNullException.ThrowIfNull(predicate);
foreach (T t in source)
if (predicate(t))
{
item = t;
return true;
}
item = default;
return false;
}
/// <summary>
/// Tries to get the first item that meets a condition from a collection.
/// </summary>
/// <typeparam name="T">Type of items in the collection</typeparam>
/// <param name="source">Collection to get the first item of</param>
/// <param name="predicate">Method that returns <see langword="true"/> if a given item meets the condition</param>
/// <param name="item">Found item</param>
/// <returns><see langword="true"/> if an item was found</returns>
public static bool TryGetFirst<T>(this IEnumerable<T> source, Predicate<T> predicate, [MaybeNullWhen(false)] out T item)
{
ArgumentNullException.ThrowIfNull(predicate);
foreach (T t in source)
if (predicate(t))
{
item = t;
return true;
}
item = default;
return false;
}