Created
March 17, 2014 02:29
-
-
Save frankmeola/9592960 to your computer and use it in GitHub Desktop.
Contiguous items list ranges
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.Collections.Generic; | |
namespace ContiguousItems | |
{ | |
public static class LinqContiguousExtensions | |
{ | |
public static IEnumerable<T> SkipUntil<T>(this IEnumerable<T> source, Predicate<T> predicate) | |
{ | |
bool startPointFound = false; | |
foreach (var current in source) | |
{ | |
startPointFound = startPointFound || predicate(current); | |
if (startPointFound) | |
{ | |
yield return current; | |
} | |
} | |
} | |
public static IEnumerable<T> SkipUntilExlusive<T>(this IEnumerable<T> source, Predicate<T> predicate) | |
{ | |
bool firstFind = false; | |
bool startPointFound = false; | |
bool canTake = false; | |
int count = 0; | |
foreach (var current in source) | |
{ | |
firstFind = predicate(current); | |
startPointFound = startPointFound || predicate(current); | |
canTake = startPointFound && count > 0; | |
if (firstFind && !canTake) | |
{ | |
count = 1; | |
continue; | |
} | |
else if(!firstFind && canTake) | |
{ | |
yield return current; | |
} | |
} | |
} | |
public static IEnumerable<T> TakeUntil<T>(this IEnumerable<T> source, Predicate<T> predicate) | |
{ | |
foreach (var current in source) | |
{ | |
if (predicate(current)) | |
{ | |
yield return current; | |
break; | |
} | |
else yield return current; | |
} | |
} | |
public static IEnumerable<T> TakeUntilExclusive<T>(this IEnumerable<T> source, Predicate<T> predicate) | |
{ | |
foreach (var current in source) | |
{ | |
if (predicate(current)) break; | |
else yield return current; | |
} | |
} | |
public static IEnumerable<T> SelectRange<T>(this IEnumerable<T> source, Predicate<T> start, Predicate<T> end) | |
{ | |
return source.SkipUntil(start).TakeUntil(end); | |
} | |
public static IEnumerable<T> SelectRangeExclusive<T>(this IEnumerable<T> source, Predicate<T> start, Predicate<T> end) | |
{ | |
return source.SkipUntilExlusive(start).TakeUntilExclusive(end); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment