Well, a simple foreach
loop should do in generalized case; let's implement the routine as enumeration:
using System.Linq;
...
private static IEnumerable<T> MyExtraction<T>(IEnumerable<T> source,
Func<T, bool> selectItem,
Func<List<T>, bool> selectGroup) {
List<T> cache = new List<T>();
foreach (T item in source) {
if (selectItem(item))
cache.Add(item);
else if (cache.Count > 0) { // if we have anything to output
if (selectGroup(cache)) // should we output?
foreach (T result in cache)
yield return result;
cache.Clear();
}
}
if (cache.Count > 0 && selectGroup(cache))
foreach (T result in cache)
yield return result;
}
Then we can use it as follow:
List<char> charlist = new List<char>() {
'b', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'b', 'b'
};
List<char> newCharList = MyExtraction(
charlist, // process charlist
item => item == 'b', // extract 'b'
group => group.Count >= 3) // take all groups which size >= 3
.ToList(); // materialize as List
// Let's have a look
Console.Write(string.Join(", ", newCharList));
Outcome: (7 items - groups of 3 and 4 itemes combined)
b, b, b, b, b, b, b