Elizabeth Dimova
Elizabeth Dimova

Reputation: 255

Get the next item in lambda expression

I checked the answered questions but none of them address the issue I have.

I just need to get the NEXT ITEM from the table Cars (sql server database) and I have the following query against the EF which kinda ignores the Skip:

var carid = value;
var car = db.Cars.Where(c => c.CarID == carid).OrderBy(c => c.CarID).Skip(1).FirstOrDefault();
Response.Write(car.CarID);

It always returns the very same element as initial value. I guess firstordefault is not the way to go.

Thank you

Upvotes: 0

Views: 283

Answers (1)

Stilgar
Stilgar

Reputation: 23571

The Correct code is probably

var carid = value;
var car = db.Cars.Where(c => c.CarID > carid).OrderBy(c=> c.CarID).FirstOrDefault();
//needs a null check before using car
Response.Write(car.CarID);

(note the > in the where)

However the fact that your previous code did return a value (as opposed to null) means that you have multiple records with the same CarID. This seems wrong.

Also note that the proper code requires autoincrementing IDs in the database.

Upvotes: 1

Related Questions