LINQ Next Item in List

Since you have a List<T> object you can use its FindIndex method instead of Where to get the index of the first matching item rather than the item itself:

int index = recommendations.FindIndex(rp =>
                                            rp.Products.Any(p => p.Product.Code == "A") 
                                         && rp.Products.Any(p => p.Product.Code == "B")
                                      );

Once you have the index you can get the next item or previous item or whatever you want.


Try this one


NEXT Item

MyList.SkipWhile(x => x != value).Skip(1).FirstOrDefault();

PREVIOUS Item note:Reverse() will not work for LINQ to SQL

 var MyList2 = MyList.ToList();
 MyList2.Reverse();
 MyList2.SkipWhile(x => x != value).Skip(1).FirstOrDefault();

Here's my current best method:

MyList.SkipWhile(item => item.Name != "someName").Skip(1).FirstOrDefault()

An earlier answer uses Skip(1).Take(1) which works, but returns a list of one result. In my case (and perhaps the OP's case), we're looking for the actual item. So my code skips until it gets to the one we're looking for (a Where would return a subset so we wouldn't have access to the next item) then skips one more and then gets the item.

Tags:

Linq