Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1822
  • Last Modified:

linq to sql - how to get next highest id in query

In linq say my query returns the first and last foo object

FOO first = dataContext.Foos.First();
FOO last = dataContext.FOOs.Last();

Great!   The FOO table has an autoincrement number which works great.

Now I want to be able to get the next FOO object with the next highest ID, so my query would be something like

FOO nextFoo = dataContext.FOOs  //get the next foo object

So my question is how to get the next FOO object with the next highest ID?
0
ToString1
Asked:
ToString1
  • 3
3 Solutions
 
withCommented:
Give this a try,

Foo nextFoo = dataContext.Foos.Top("1").OrderBy(f => f.ID).FirstOrDefault(f => f.ID > firstfoo.ID)

I think that should get you the next foo with an ID greater than "firstfoo", limited to just 1 record.
0
 
Fernando SotoRetiredCommented:
Are you looking for the next Foo ID after this, FOO last = dataContext.FOOs.Last();, which has not yet been create?

0
 
ToString1Author Commented:
hi

Each time I want to call the next foo.ID

No they have all been created and also the ID is autoincrement in database
0
 
Fernando SotoRetiredCommented:
Hi ToString1;

Then this should do what you need. Although you can remove the OrderBy method call because it is the index on the table and should already be sorted.

Fernando
// The ID used to get the next ID in the database table
int id = 5;
FOO last = dataContext.FOOs.Where(f => f.ID >= id).OrderBy(f => f.ID).Skip(1).Take(1);

Open in new window

0
 
Fernando SotoRetiredCommented:
Even better, this.
// The ID used to get the next ID in the database table
int id = 5;
FOO last = dataContext.FOOs.Where(f => f.ID > id).Take(1);

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now