WherePrevious

public static class CollectionExtensions
{
    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));
			
        if (!collection.Any()) 
	   yield break;
			
        var items = collection
            .Zip(collection.Skip(1), (previous, item) => new { previous, item })
            .Where(zip => predicate(zip.previous, zip.item))
            .Select(zip => zip.item);
        
        foreach (var item in items)
        {
            yield return item;
        }
    }
}
Example:
var items = new List<int> { 1, 5, 7, 3, 10, 9, 6}; 
var result = items.WherePrevious((first, second) => second > first);

Description

Compare Through a predicate every element of a list with the previous one

Details

Double click on the code to select all.

 

;