Home > Mobile >  Find with starting index?
Find with starting index?

Time:08-03

I'm trying to figure out how to find the "next matching" object in a C# List<MyObject> where I have a starting index.

Meaning suppose I have the following list.

List<MyObject> myList = new List<MyObject>
{
  new MyObject
  {
    isActive = true
  },
  new MyObject
  {
    isActive = false
  },
  new MyObject
  {
    isActive = true
  },
}

And I want to do myList.Find(x => x.IsActive) /// where index is greater than 0??

CodePudding user response:

You can use Linq Skip and FirstOrDefault to skip the first object and get the first occurence of an object that is active or it's default value, or you can use First if you want an exception to be thrown if no match is found:

myList.Skip(1).FirstOrDefault(x => x.IsActive);

CodePudding user response:

There is a FindIndex method on Lists that accepts a starting index value and a predicate so you could do something like this:

var idx = myList.FindIndex(1, x => x.IsActive)

CodePudding user response:

You can get the index using FindIndex and then retrieve the item:

var idx = myList.FindIndex(2, x => x.IsActive);
var item = idx >= 0 ? myList[idx] : default(MyObject);

As an alternative, you can use Skip and FirstOrDefault:

var item = myList
  .Skip(123)
  .FirstOrDefault(x => x.IsActive);
  • Related