❔ LINQ: Group and extract all consecutive elements from List that match predicate
Example:
Expected output:
Is there such functionality in LINQ?
Expected output:
Is there such functionality in LINQ?
5
4
2
4
1List<int> ints = new() {6,3,1,1,1,1,1,2,7,8,1,1,1,1,3,2,5,1,1,9,8,1,1,1,1,4,7,8,1}
var output = ints.GroupConsecutive().Where((g) => g.Key == 1); // Not a real function
foreach (var o in output)
{
Console.WriteLine(o.Count);
}foreach, will work with any IEnumerable<TValue, int>Aggregate with a result value that holds a list of tuples representing the key and the count. For each iteration you'd compare the current key with the most recent key in the result value. If the keys are different, push a new tuple onto the result with the new key and a count of zero-1s?maybe type-1?-1?<TValue, int>Aggregatemaybestatic List<T> WhoopsAddReturnsVoid<T>(this List<T> list, T val) {
list.Add(val);
return list;
}
var ints = new List<int>{6,3,1,1,1,1,1,2,7,8,1,1,1,1,3,2,5,1,1,9,8,1,1,1,1,4,7,8,1};
var keysAndCounts = ints.Aggregate(
(new List<(int, int)>(), (-1,-1)),
(carry, current) =>
carry switch {
(var result, (-1, -1)) =>
(result, (current, 1)),
(var result, var (key, count)) =>
current == key
? (result, (key, count + 1))
: (result.WhoopsAddReturnsVoid((key, count)), (current, 1))
},
carry => carry.Item1.WhoopsAddReturnsVoid(carry.Item2));
var all1Counts = keysAndCounts
.Where(pair => pair.Item1 == 1)
.Select(pair => pair.Item2);
foreach (var val in all1Counts) {
Console.WriteLine(val);
}