Selecting items in an ordered list after a specific entry

I have an ordered list of objects. I can easily find an item in a list using the following code:

purchaseOrders.FirstOrDefault(x => x.OurRef.Equals(lastPurchaseOrder, StringComparison.OrdinalIgnoreCase))

      

What I want to do is select all the items in the list that appear after this entry. What's the best way to achieve this? Would you like to get the index of this element and select a range?

+3


source to share


3 answers


It sounds like you want SkipWhile

:

var orders = purchaseOrders.SkipWhile(x => !x.OurRef.Equals(...));

      

Once the iterator has stopped skipping, it does not evaluate the predicate for subsequent records.



Note that this code will contain an entry that does not match the predicate, i.e. the one who has this link. It will basically give you all the records from this order onwards. You can always use .Skip(1)

if you want to skip this:

// Skip the exact match
var orders = purchaseOrders.SkipWhile(x => !x.OurRef.Equals(...)).Skip(1);

      

It will be linear, mind you ... if the list is ordered by x.OurRef

, you can find the index with a binary search and accept the range from there onwards ... but I wouldn't do that unless you find that simpler code is causing problems.

+6


source


You should probably take a look at the LINQ combination of Reverse and TakeWhile methods if I understand your question correctly.

It may look like purchaseOrder.Reverse().TakeWhile(x => !x.OurRef.Equals(lastPurchaseOrder, StringComparison.OrdinalIgnoreCase))

.



Sorry if the code is unformatted, I'm from mobile internet right now.

+2


source


Maybe you want something like this:

int itemIndex = list.IndexOf(list.FirstOrDefault(x => x.OurRef.Equals(lastPurchaseOrder, StringComparison.OrdinalIgnoreCase));
var newList = list.Where((f, i) => i >= itemIndex);

      

0


source







All Articles