Last active
April 30, 2018 13:20
-
-
Save zelinskiy/db31557bb414679e1b520c980c34046b to your computer and use it in GitHub Desktop.
Usefull IEnumerable extensions: AllSame, Fold
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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