Linq: X objects in line

I need help with a linq query that will return true if the list contains x objects in a row when the list is sorted by date.

So:

myList.InARow(x => x.Correct, 3) 

will return true if string 3 is specified with the rule == true.

I don’t know how to do it.

+4
source share
3 answers

Nothing is built into linq, which easily handles this case. But creating a simple extension method is quite simple.

 public static class EnumerableExtensions { public IEnumerable<T> InARow<T>(this IEnumerable<T> list, Predicate<T> filter, int length) { int run = 0; foreach (T element in list) { if (filter(element)) { if (++run >= length) return true; } else { run = 0; } } return false; } } 
+3
source

Using the GroupAdjacent extension, you can do:

 var hasThreeConsecutiveCorrect = myList.GroupAdjacent(item => item.Correct) .Any(group => group.Key && group.Count() >= 3); 

Here's another way with the Rollup extension (crossing between Select and Aggregate), which is slightly more economical:

 var hasThreeConsecutiveCorrect = myList.Rollup(0, (item, sum) => item.Correct ? (sum + 1) : 0) .Contains(3); 
+8
source

Update

 myList.Aggregate(0, (result, x) => (result >= 3) ? result : (x.Correct ? result + 1 : 0), result => result >= 3); 

The generalized version :

 myList.Aggregate(0, (result, x) => (result >= length) ? result : (filter(x) ? result + 1 : 0), result => result >= length); 
+2
source

All Articles