Akrem
Akrem

Reputation: 4652

Search in part of the list by LINQ

I want to know if there's a way to search from a specific index in LINQ

This is what i want to do for example :

 //search after the 4th element if exist any true
     bool result = myList.Any(a=>a.flagTodo) 
// in my case I want to do like:  myList.where(a=>a.index >4).Any(a=>a.flagTodo)

there's any way to do it in the same linq ?

Upvotes: 1

Views: 76

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can use Enumerable.Skip to bypass specified number of elements in sequence:

bool result = myList.Skip(4).Any(a => a.flagTodo);

BTW you don't need to verify list length - if there is less than 4 items, result will be false - Skip(4) will return empty sequence. And Any returns false because none of elements in sequence satisfies condition (sequence is empty).

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460288

Either use Skip as others have mentioned or pass the index so that you can use it in Any

bool result = myList.Select((obj, index) => new { obj, index })
                    .Any(x => x.index > 4 && x.obj.flagTodo);  

Upvotes: 0

Ravi Y
Ravi Y

Reputation: 4376

You can skip the first 4 elements.

 bool result = myList.Skip(4).Any(a => a.flagTodo);

But you need to check on your list length first before calling this statement.

Upvotes: 4

Related Questions