简体   繁体   中英

Linq: X objects in a row

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.

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);

There is nothing built into linq that handles this case easily. But it is a relatively simple matter to create your own extension method.

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;
    }
}

Updated :

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

Generalized version :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM