diff --git a/LightweightIocContainer/EnumerableExtension.cs b/LightweightIocContainer/EnumerableExtension.cs index 6edecd6..35ccd6a 100644 --- a/LightweightIocContainer/EnumerableExtension.cs +++ b/LightweightIocContainer/EnumerableExtension.cs @@ -13,7 +13,7 @@ internal static class EnumerableExtension /// The given to return if the contains no elements /// The given /// The first element of the , or a new instance of a given if the contains no elements - public static TSource FirstOrGiven(this IEnumerable source) where TGiven : TSource, new() => + public static TSource FirstOrGiven(this IReadOnlyCollection source) where TGiven : TSource, new() => source.TryGetFirst(null); /// @@ -24,7 +24,7 @@ internal static class EnumerableExtension /// The given /// A function to test each element for a condition /// The first element of the that satisfies a condition, or a new instance of the given if no such element is found - public static TSource FirstOrGiven(this IEnumerable source, Func predicate) where TGiven : TSource, new() => + public static TSource FirstOrGiven(this IReadOnlyCollection source, Func predicate) where TGiven : TSource, new() => source.TryGetFirst(predicate); /// @@ -35,17 +35,12 @@ internal static class EnumerableExtension /// The given /// A function to test each element for a condition /// The first element of the or a new instance of the given when no element is found - private static TSource TryGetFirst(this IEnumerable source, Func? predicate) where TGiven : TSource, new() - { - try - { - return predicate == null ? source.First() : source.First(predicate); - } - catch (Exception) - { - return new TGiven(); - } - } + private static TSource TryGetFirst(this IReadOnlyCollection source, Func? predicate) where TGiven : TSource, new() => + predicate is null ? + !source.Any() ? new TGiven() + : source.First() + : source.Any(predicate) ? source.First(predicate) + : new TGiven(); /// /// Executes an for each item in an