using System; using System.Collections; using System.Collections.Generic; namespace BlueWest.Collections { public static class IEnumerableExtensions { public static TSource? FirstOrNull(this TSource[] source, Func predicate) where TSource : struct => source.TryGetFirst(predicate); private static TSource? TryGetFirst(this TSource[] source, Func predicate) where TSource : struct { for (var i = 0; i < source.Length; i++) { if (predicate(source[i])) { return source[i]; } } return null; } public static TSource FirstOrNullRef(this IEnumerable source, Func predicate) where TSource : class => source.TryGetFirstClass(predicate); public static TSource? FirstOrNullStruct(this IEnumerable source, Func predicate) where TSource : struct => source.TryGetFirstStruct(predicate); private static TSource? TryGetFirstStruct(this IEnumerable source, Func predicate) where TSource : struct { foreach (TSource obj in source) { if (predicate(obj)) { return obj; } } return null; } private static TSource TryGetFirstClass(this IEnumerable source, Func predicate) where TSource : class { foreach (TSource obj in source) { if (predicate(obj)) { return obj; } } return null; } } }