ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

WherePrevious

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

Source

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);

Author: Emanuele Rossi

Submitted on: 19 jul. 2018

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 4434