Arpit Gupta
Arpit Gupta

Reputation: 1277

LINQ - Fetch items from list starting from specific index

With the help of LINQ, I need to fetch items from a list based on a condition. For that it should consider items only from (provided index - 3) to provided index (dynamically).

For example, a list contains items {1,3,5,7,9,11,13}. If provided index is 4, the it should consider total three indexes starting from index 2 to ending at index 4. Among these three items, it should be filter them with a condition - say, Item should be greater than 5.

The result should be - {7,9}

What I tried is, which is wrong and I am stuck:

list.Select(item => list.Select(index => item[index - 3] && item > 5).ToList());

Upvotes: 4

Views: 6632

Answers (2)

grek40
grek40

Reputation: 13458

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503889

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.

Upvotes: 19

Related Questions