I made an extension method to find the number of consecutive values ββin the collection. Since it is generic, I allow the caller to define an "increment", which is Func <>, which must increment the value to check for the presence of the "next" value.
However, if the caller passes the wrong increment (i.e. x => x), it will cause an infinite recursive loop. Any suggestions on clean ways to prevent this?
public static int CountConsecutive<T>(this IEnumerable<T> values, T startValue, Func<T, T> incrementor) { if (values == null) { throw new ArgumentNullException("values"); } if (incrementor == null) { throw new ArgumentNullException("incrementor"); } var nextValue = incrementor(startValue); return values.Contains(nextValue) ? values.CountConsecutive(nextValue, incrementor) + 1 : 1; }
user718642
source share