my requirement is to implement a way to filter a collection of elements based on a value of previous one. For example to only select a number that is larger than the previous one. I don't currently know of any LINQ method that would allow me to do such a thing, so I decided to create one.
This is a code I have so far:
public static IEnumerable<T> WherePrevious<T>(this IEnumerable<T> collection, Func<T, T, bool> predicate)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
T previous = default(T);
bool firstIteration = true;
foreach (var item in collection)
{
if (firstIteration)
{
previous = item;
firstIteration = false;
yield return item;
}
else
{
if (predicate(previous, item))
{
yield return item;
}
previous = item;
}
}
}
Are there any ways to improve my code in terms of performance, readability or more generalization to make?
For example I'm not sure if it's clear to the caller of the method what the predicate inputs actually are