Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: X objects in a row

Tags:

arrays

c#

linq

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

so like this:

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

would return true if there are 3 in a row with the property correct == true.

Not sure how to do this.

like image 819
Chris Kooken Avatar asked Dec 12 '22 15:12

Chris Kooken


1 Answers

Using a GroupAdjacent extension, you can do:

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

Here's another way with a Rollup extension (a cross between Select and Aggregate) that's somewhat more space-efficient:

var hasThreeConsecutiveCorrect 
    = myList.Rollup(0, (item, sum) => item.Correct ? (sum + 1) : 0)
            .Contains(3);
like image 156
Ani Avatar answered Dec 28 '22 04:12

Ani