48 lines
1.3 KiB
C#
48 lines
1.3 KiB
C#
namespace PkmnLib.Static.Utils;
|
|
|
|
/// <summary>
|
|
/// Extension methods for <see cref="IEnumerable{T}"/>.
|
|
/// </summary>
|
|
public static class EnumerableHelpers
|
|
{
|
|
/// <summary>
|
|
/// Returns all elements of the enumerable that are not null.
|
|
/// </summary>
|
|
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> enumerable) where T : class =>
|
|
enumerable.Where(x => x is not null)!;
|
|
|
|
/// <summary>
|
|
/// Finds the index of a value in an enumerable. Returns -1 if the value is not found.
|
|
/// </summary>
|
|
public static int IndexOf<T>(this IEnumerable<T> enumerable, T value)
|
|
{
|
|
var index = 0;
|
|
foreach (var item in enumerable)
|
|
{
|
|
if (item is null)
|
|
{
|
|
if (value is null)
|
|
return index;
|
|
continue;
|
|
}
|
|
if (item.Equals(value))
|
|
return index;
|
|
|
|
index++;
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes all elements from a list that match the given predicate.
|
|
/// </summary>
|
|
public static void RemoveAll<T>(this IList<T> list, Func<T, bool> predicate)
|
|
{
|
|
for (var i = list.Count - 1; i >= 0; i--)
|
|
{
|
|
if (predicate(list[i]))
|
|
list.RemoveAt(i);
|
|
}
|
|
}
|
|
} |