score:18

Accepted answer

It sounds like you just want a mix of Skip and Take, filtering with Where:

var query = list.Skip(index - 3)    // Start at appropriate index
                .Take(3)            // Only consider the next three values
                .Where(x => x > 5); // Filter appropriately

Personally it seems a little odd to me that the index would be the end point rather than the start point, mind you. You might want to see if other pieces of code would benefit from changing that.

score:3

An alternative to Skip and Take would be to include the item index in the Where clause

list.Where((x, i) => // x is the list item, i is its index
    i > (index - 3) && i <= index && // index bounds
    x > 5 // item condition
)

For you specific requirement with a single sub-range of items, I'd go with the Skip and Take, but if you ever need a more complex condition on the item index, you can utilize this Where overload.


Related Articles