Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Next Item in List

Tags:

linq

Taking a look at my question HERE, I now want to return the next recommendation object (after) the one that matches the criteria.

So say I found item 6 out of 10, I'd like the query to return item 7 instead.

Or is there a better way?

like image 683
griegs Avatar asked Apr 21 '10 03:04

griegs


3 Answers

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.

like image 93
Jeremy Foster Avatar answered Nov 11 '22 00:11

Jeremy Foster


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.

like image 27
EMP Avatar answered Nov 11 '22 00:11

EMP


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();
like image 15
Abdul Saboor Avatar answered Nov 10 '22 23:11

Abdul Saboor