Apostrofix
Apostrofix

Reputation: 2180

Linq query to select next id from a database table

is there any way to select the next object from a database table without knowing its' Id?

The database table looks like that and it's called Jobs:

Id | ScheduleId | DateHappened | Status
 1 |   150      | 2014-05-30   | Done
 2 |   150      | 2014-06-10   | Done
 3 |   150      | 2014-06-13   | Done

I am trying to get the Id of each Job and use it to insert it in a log table. I know that this is some sort of a "against the rules" request, but at this stage I can't afford to make any big changes.

I know that in this case I can select the first and the last elements by using the .First() and .Last() functions, but what about anything in between?

Upvotes: 0

Views: 1729

Answers (3)

Dan Puzey
Dan Puzey

Reputation: 34200

It seems that you're assuming that the jobs are returned in order of id, which might be a big assumption...

However, you also mention .First() and .Last() and have tagged "Linq", so I assume you've already got your data from the database in some way. I'll assume that you have an IQueryable called queryResult that you are calling .First() and .Last() on for the remainder of this answer...

If you just want to go through every record, you perhaps don't need Linq at all: just use a foreach:

foreach (var row in queryResult)
{
    ....
}

Alternatively, if you don't want every method, you might be able to use Linq's .Skip():

queryResult.Skip(10).First() // gives you the 11th record

Or, if you just want to log all of the IDs as a single item, you could use Linq's Select to get a list of just the IDs:

queryResult.Select(x => x.Id)

If all you're interested in is the ID, but you need to loop individually, then you can potentially use the result of this .Select in combination with the other solutions to make your code more efficient. If you're using an ORM with deferred execution (like EF) then a query like this is more efficient than pulling the entire database and then using a foreach:

var ids = queryResult.Select(x => x.Id);
foreach (var id in ids) 
{
    ....
}

Upvotes: 1

Christos
Christos

Reputation: 53958

You could try this one:

var ids = db.Jobs.Select(x=>x.Id);

or

var ids = (from job in db.Jobs
          select job.Id);

Upvotes: 2

usr
usr

Reputation: 171178

It seems you want all IDs from all the jobs:

db.Jobs.Select(j => j.ID).ToList()

Upvotes: 2

Related Questions