0

I get max id

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

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

cuongle
  • 74,024
  • 28
  • 151
  • 206
CyberDx
  • 51
  • 7
  • 2
    next after previous = current? and what do you mean by "previous" and "next after previous"? do you mean "top 3 values" - i.e. Max, next smaller, and another one? or next and previous IDs for every record in the set? – aiodintsov Sep 08 '12 at 20:40
  • Use OrderBy,Skip and First/FirstOrDefault. – Tim Schmelter Sep 08 '12 at 20:47
  • visit this question http://stackoverflow.com/questions/1811846/how-to-get-the-second-highest-number-in-an-array-in-visual-c – Jignesh Thakker Sep 09 '12 at 03:55

3 Answers3

2

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 }
Martin
  • 2,302
  • 2
  • 30
  • 42
1

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.

Andrew Walters
  • 4,763
  • 6
  • 35
  • 49
0

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).

firepol
  • 1,731
  • 22
  • 39