Created
November 9, 2016 19:34
-
-
Save fabiomaulo/25fd7804ee1f28586743674b3daba7fd to your computer and use it in GitHub Desktop.
Some useful extensions of IEnumerable
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> Yield<T>(this T source) | |
{ | |
yield return source; | |
} | |
public static IEnumerable<IEnumerable<TSource>> PagedBy<TSource>(this IEnumerable<TSource> source, int pageSize) | |
{ | |
if (source == null) | |
{ | |
throw new ArgumentNullException(nameof(source)); | |
} | |
if (pageSize <= 0) | |
{ | |
yield break; | |
} | |
using (var enumerator = source.GetEnumerator()) | |
{ | |
while (enumerator.MoveNext()) | |
{ | |
var page = new List<TSource>(pageSize) {enumerator.Current}; | |
while (page.Count < pageSize && enumerator.MoveNext()) | |
{ | |
page.Add(enumerator.Current); | |
} | |
yield return page.AsEnumerable(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment