Last active
November 5, 2019 09:14
-
-
Save axelheer/97c152e569dd80f1c34c to your computer and use it in GitHub Desktop.
Enumerable LINQ extensions
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 EnumerableExtensions | |
{ | |
public static IEnumerable<T> Flatten<T>(this T value, Func<T, T> inner, T tail = default(T)) | |
{ | |
var comparer = EqualityComparer<T>.Default; | |
while (!comparer.Equals(value, tail)) | |
{ | |
yield return value; | |
value = inner(value); | |
} | |
} | |
public static IEnumerable<T> Flatten<T>(this T value, Func<T, IEnumerable<T>> inner) | |
{ | |
foreach (var i in inner(value)) | |
foreach (var j in Flatten(i, inner)) | |
yield return j; | |
yield return value; | |
} | |
public static IEnumerable<T> Each<T>(this IEnumerable<T> items, Action<T> action) | |
{ | |
foreach (var i in items) | |
action(i); | |
return items; | |
} | |
public static IEnumerable<T> Each<T>(this IEnumerable<T> items, Action<T, int> action) | |
{ | |
var index = 0; | |
foreach (var i in items) | |
action(i, index++); | |
return items; | |
} | |
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> items, T item) | |
{ | |
yield return item; | |
foreach (var i in items) | |
yield return i; | |
} | |
public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T item) | |
{ | |
foreach (var i in items) | |
yield return i; | |
yield return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment