RAK
RAK

Reputation: 283

How to find an element in the List from a specific index upto the end?

How can I search for an element in a List of Type starting from a specific element?

I can achieve the same using the for loop as follows:

bool found = false;
for(int i=counter+1;i<=lstTags.Count()-1;i++)
   {
    if (lstTags[i].PlateFormID == plateFormID)
      {
        found = true;
        break;
       }
    }

However, I want to know if it can be done in a more efficient way through a built-in feature like:

var nextItem=lstTags.FirstOrDefault(a=>a.PlateFormID==plateFormID, startIndex); 

Upvotes: 1

Views: 666

Answers (2)

Wei Lin
Wei Lin

Reputation: 3811

You can use Where((obj,index)=>yourLogic)

Code:

var nextItem=lstTags.Where((a,index) => a.PlateFormID==plateFormID && index > startIndex ).FirstOrDefault(); 

EX

var datas = new[] { "item1","item2","item3"};
var data = datas.Where((obj,index) => index>1 ).FirstOrDefault(); //item3

PS

  • Index start with 0

Upvotes: 2

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can use Enumerable.Skip:

var nextItem = lstTags.Skip(startIndex).FirstOrDefault(a => a.PlateFormID == plateFormID);

This will filter out first startIndex elements and then find the first matching PlateFormID in the filtered enumerable.

Upvotes: 6

Related Questions