[ACCEPTED]-Find next record in a set: LINQ-linq

Accepted answer
Score: 39

Without re-ordering (note I edit slightly 2 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 1 data was a set of objects, something like:

var next = data.SkipWhile(obj => obj.Id != last).Skip(1).First();
Score: 4
int currentId = 25;
var next = yourCollection.Where(i => i.Id > currentId).OrderBy(i => i.Id).First();

0

Score: 2

There are quite a few solution. I suggest 5 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 4 the ids in the order they appear in the 3 collection, you could use the following.

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

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

More Related questions