Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next record in a set: LINQ

Tags:

c#

linq

I have a list of objects which all have an id property

E.g

1, 10, 25, 30, 4

I have a currentId and I need to find the next Id in the list

So for example current Id is set to 25, I need to return the object with an id of 30. The one after that would be 4.

How would I do this elegantly in LINQ?

EDIT

The list is ordered by a "sort" property. So you cannot just order by id, as that would mess up the order.

like image 225
Chris James Avatar asked Aug 26 '09 10:08

Chris James


2 Answers

Without re-ordering (note I edit slightly as I think I misread the question):

int[] data = {1, 10, 25, 30, 4};
int last = 25;
var next = data.SkipWhile(i => i != last).Skip(1).First();

Obviously, if data was a set of objects, something like:

var next = data.SkipWhile(obj => obj.Id != last).Skip(1).First();
like image 101
Marc Gravell Avatar answered Oct 01 '22 01:10

Marc Gravell


int currentId = 25;
var next = yourCollection.Where(i => i.Id > currentId).OrderBy(i => i.Id).First();
like image 33
RaYell Avatar answered Oct 01 '22 00:10

RaYell