8

am trying to get a row (object) based on the max of RollNumber which is a long Datatype field. i expect it to return a null object in case there isn't any so i used SingleorDefault.But it seems my query is all wrong(work in progress on linq here). here is the query:

SchoolContextExpress db = new SchoolContextExpress();
        Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault();

thanks for reading this.

5
  • Looks ok to me. What's the problem? Feb 29, 2012 at 10:48
  • Well, works fine here! Do you get an error?
    – madC
    Feb 29, 2012 at 10:52
  • Contains more than one element Feb 29, 2012 at 10:52
  • Do you have duplicate roll numbers? Feb 29, 2012 at 10:56
  • Ahah! there are empty, index allows empty row. the reason why they are left empty is because in my business logic i would like to validate the registration before issuing the roll number. So on registration , everything is saved but the rollnumber is left empty (zero in this long context). How can i work around this? Feb 29, 2012 at 11:00

2 Answers 2

11

To work with empty RollNumber...

Profile profile = db.Profiles.Where(p => p.RollNumber !=0 &&  p.RollNumber == db.Profiles.Max(r=>r.RollNumber)).SingleOrDefault();

Or you may want to consider...

Profile profile = db.Profiles.Where(p => p.RollNumber == db.Profiles.Where(p1 => p1.RollNumber != 0).Max(r=>r.RollNumber)).SingleOrDefault();
1
  • i guess i would do different from zero then since RollNumber is long. is that ok? Feb 29, 2012 at 11:06
3

Another way to do beside the first answer:

Profile profile = db.Profiles.OrderByDescending(p => p.RollNumber).FirstOrDefault();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.