Reputation: 4406
I have a list of lets say 10 items on the first call:
var myList = GetMyList();
okay now I get the item I want from this list:
myList.FirstOrDefault(x => x.Id == id);
Now I go to the web page and do stuff.
Now I am back: The list Could have changed by this point if anything was deactivated through a rest call in my API. (I rebuild the current list in the constructor)
public OneItemFromMyList Get(int id)
{
//Here I need the next item in the list after the one with the above Id
}
So how do I get that one. I do not want to repeat one that I retrieved before and I don't want to move outside of the list so I would need to start over if I am on the last position.
Any Suggestions?
Upvotes: 1
Views: 69
Reputation: 117134
I think this will work for you:
var nextId =
myList
.SkipWhile(x => x != id) //skip until x == id
.Skip(1) // but I don't want x == id so skip one more
.Concat(myList) // but item could be removed or I hit the end so restart
.First(); // the first item is the one I want!
Upvotes: 1
Reputation: 726849
To get an item immediately after the one with the specific id
, do this:
var nextItem = myList.SkipWhile(x => x.Id != id).Take(2).LastOrDefault();
Note that this may not produce an item, if either of the following is true:
x.Id == id
is not there, orx.Id == id
is the last item in the list.Upvotes: 1