CodeLiturgy.Dashboard/BlueWest.WebApi/Tools/IEnumerableExtensions.cs

44 lines
1.3 KiB
C#

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