8

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

Community
  • 1
  • 1
griegs
  • 22,624
  • 33
  • 128
  • 205

1 Answers1

18

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.
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
  • This assumes that the items are in order, which, according to the question, they aren't. – Ant P Jun 21 '13 at 04:49
  • Actually this works because I use items.TakeWhile(x => x.id != id).LastOrDefault(); and this then selects the previous record – griegs Jun 21 '13 at 04:52
  • Sweet. (Except change it to the form given by griegs above.) @AntP No it doesn't. Maybe you misinterpreted the question. – Jim Balter Jun 21 '13 at 04:55
  • I think OP meant that they aren't **sorted** or that the set is not **continuous**, so you can't stop at the item that has one less ID than "current". This solution holds. – Tormod Jun 21 '13 at 05:04
  • Hmmm, seems I have misunderstood the question, but "I need to get the previous person to the id that was provided to me," is a little ambiguous. – Ant P Jun 21 '13 at 06:13
  • it didn't but not because your solution was bad i think. i think it was to do with the list i was being given. so +1 and correct answer because i think it is technically right. thanks. – griegs Jun 22 '13 at 11:42