Skip to content

Instantly share code, notes, and snippets.

@zelinskiy
Last active April 30, 2018 13:20
Show Gist options
  • Save zelinskiy/db31557bb414679e1b520c980c34046b to your computer and use it in GitHub Desktop.
Save zelinskiy/db31557bb414679e1b520c980c34046b to your computer and use it in GitHub Desktop.
Usefull IEnumerable extensions: AllSame, Fold
public static class MyExtensions
{
public static T1 Fold<T1, T2>(this IEnumerable<T2> xs, Func<T1,T2,T1> func, T1 acc)
{
if (xs.Count() == 0) return acc;
else return xs.Skip(1).Fold(func, func(acc, xs.First()));
}
public static bool AllSame<T>(this IEnumerable<T> xs)
{
return xs.AllSame(x => x);
}
public static bool AllSame<T, TSel>(this IEnumerable<T> xs, Func<T,TSel> selector)
{
if (xs == null) throw new ArgumentNullException(nameof(xs));
var enumerator = xs.GetEnumerator();
var toCompare = default(TSel);
if (enumerator.MoveNext())
{
toCompare = selector(enumerator.Current);
}
while (enumerator.MoveNext())
{
if (!toCompare.Equals(selector(enumerator.Current)))
{
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment