CyberDx
CyberDx

Reputation: 51

linq previous next item?

I get max id

db.info_dbs.Max(u => u.id);

How I can get previous id and (next id (after previous))

Upvotes: 0

Views: 893

Answers (3)

firepol
firepol

Reputation: 1751

Given an ID (in my case, of a picture), here how to get the next picture id and the previous picture id. I use these 2 helper methods:

public int GetPreviousPictureId(int id)
{
    var picture = db.Pictures.Where(x => x.Id < id).OrderByDescending(x => x.Id).FirstOrDefault();

    if (picture != null)
        return picture.Id;

    return 0;
}

public int GetNextPictureId(int id)
{
    var picture = db.Pictures.Where(x => x.Id > id).OrderBy(x => x.Id).FirstOrDefault();

    if (picture != null)
        return picture.Id;

    return 0;
}

To get the previous, I filter the pictures by taking only the ones with a lower id, order descending by id so that the first element of the list (FirstOrDefault) is the one I need.

To get the next, I do the opposite. I filter the pictures by taking only the ones with a higher id, order ascending by id, so that the first element of the list is the one I need.

As you can see I check for null and return the id if not null. return 0 if no pictures found. Some developers prefer to return -1 if not found. Up to you.

The first picture of the DB has no previous one. The last picture of the DB has no next one.

Hope this helps (should actually answer the question).

Upvotes: 0

Martin
Martin

Reputation: 2300

This orders the collection by Id decending, skips the first one, and grap the next in the collection. Is that what you're looking for?

var collection = new[]
                        {
                            new { Id = 1 },
                            new { Id = 3 },
                            new { Id = 2 },
                            new { Id = 5 }
                        };

var secondHighestIdValue = collection.OrderByDescending(x => x.Id).Skip(1).First();

Console.WriteLine(secondHighestIdValue); // { Id = 3 }

Upvotes: 2

Andrew Walters
Andrew Walters

Reputation: 4803

Is this Id field an identity column? Previous would be Max(Id) - 1 and the next Id would be Max(id) + 1.

But, working with identity columns like this would be a bad idea, because you can have many transactions running in the database at the same time and aren't guaranteed that your calculated next/previous values will be correct by the time you go to use them later.

If you need anything else let me know.

Upvotes: 1

Related Questions