tags:

views:

121

answers:

3

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.

+1  A: 
int currentId = 25;
var next = yourCollection.Where(i => i.Id > currentId).OrderBy(i => i.Id).First();
RaYell
Would mess up the order, sorry - have edited the question to clear it up
qui
A: 

There are quite a few solution. I suggest something like the following.

var next = items
    .Where(item => item.Id > currentId)
    .OrderBy(item => item.Id)
    .First();

var next = items
    .OrderBy(item => item.Id)
    .First(item => item.Id > currentId);

If you want the ids in the order they appear in the collection, you could use the following.

var next = items
    .SkipWhile(item => item.Id != currentId)
    .Skip(1)
    .FirstOrDefault();

If this returns null, you have tried to get next item of the last item.

Daniel Brückner
+6  A: 

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();
Marc Gravell
+1 Very clever.
Andrew Hare
Yeah the latter is what i went with, thanks.
qui
Also, if this got to the end of the list and tried to skip, would it throw an exception or just return null. Do i need to check for this?
qui
as it stands, it would throw - but you could use `FirstOrDefault` instead, which won't throw.
Marc Gravell