If I have a list of items, and say the "id" is unique, but not necessarily sequential, is there a way to find the previous entity in say either a List or an IEnumerable?
So I may have a list of people, and they each have an id and they are sorted in an order I am not aware of. All I get is the list and the id of the person.
Now I need to get the previous person to the id that was provided to me.
Is there a nice LINQ way to do this or do I simply find the record and get the previous one in a ForEach?
edit I just found this, is this the best approach?
Calculate difference from previous item with LINQ
I think you need this
items.TakeWhile(x => x.id != id).LastOrDefault();
Enumerable.TakeWhile
Method returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.default
from it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With