Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous record to current one using LINQ

Tags:

c#

linq

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

like image 779
griegs Avatar asked Jun 21 '13 04:06

griegs


1 Answers

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.
  • We take the last or default from it.
like image 145
Bhushan Firake Avatar answered Nov 14 '22 02:11

Bhushan Firake