Created
January 29, 2015 11:04
-
-
Save markusjohnsson/af1a5c651f453621e217 to your computer and use it in GitHub Desktop.
Linq: lists of lists
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
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
public static class EnumerableExtractRangeEx | |
{ | |
public static IEnumerable<IEnumerable<T>> ExtractRanges<T>(this IEnumerable<T> source, Func<T, bool> rangePredicate) | |
{ | |
using (var enumerator = source.GetEnumerator()) | |
{ | |
while (enumerator.MoveNext()) | |
{ | |
if (rangePredicate(enumerator.Current)) | |
yield return YieldWhileTrue(enumerator, rangePredicate); | |
} | |
} | |
} | |
public static IEnumerable<T> YieldWhileTrue<T>(IEnumerator<T> enumerator, Func<T, bool> predicate) | |
{ | |
do | |
{ | |
yield return enumerator.Current; | |
} | |
while (enumerator.MoveNext() && predicate(enumerator.Current)); | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
foreach (var r in | |
new [] { 1, 3, 4, 2, 8, 12, 7, 2, 9, 3, 8, 3, 7, 2, 6, 7, 5, 8, 9, 4, 3, 1, 2, 4 } | |
.ExtractRanges(x => x % 2 == 0).Select(r => r.ToList())) | |
{ | |
Console.WriteLine("Count: " + r.Count()); | |
foreach (var n in r) | |
Console.WriteLine(n); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment