2021-12-10 03:04:48 +03:00
|
|
|
|
using System;
|
2021-12-06 02:49:27 +03:00
|
|
|
|
using System.Collections;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
2021-12-10 03:04:48 +03:00
|
|
|
|
namespace BlueWest.Collections
|
2021-12-06 02:49:27 +03:00
|
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-04 03:59:04 +03:00
|
|
|
|
public static TSource FirstOrNullRef<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) where TSource : class =>
|
|
|
|
|
source.TryGetFirstClass(predicate);
|
|
|
|
|
|
|
|
|
|
public static TSource? FirstOrNullStruct<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) where TSource : struct =>
|
|
|
|
|
source.TryGetFirstStruct(predicate);
|
2021-12-06 02:49:27 +03:00
|
|
|
|
|
2022-08-04 03:59:04 +03:00
|
|
|
|
private static TSource? TryGetFirstStruct<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) where TSource : struct
|
2021-12-06 02:49:27 +03:00
|
|
|
|
{
|
|
|
|
|
foreach (TSource obj in source)
|
|
|
|
|
{
|
|
|
|
|
if (predicate(obj))
|
|
|
|
|
{
|
|
|
|
|
return obj;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2022-08-04 03:59:04 +03:00
|
|
|
|
private static TSource TryGetFirstClass<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) where TSource : class
|
|
|
|
|
{
|
|
|
|
|
foreach (TSource obj in source)
|
|
|
|
|
{
|
|
|
|
|
if (predicate(obj))
|
|
|
|
|
{
|
|
|
|
|
return obj;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-06 02:49:27 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|