How to select a row(object) based on max of a field Entity Framework 4.1

10,455

Solution 1

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();

Solution 2

Another way to do beside the first answer:

Profile profile = db.Profiles.OrderByDescending(p => p.RollNumber).FirstOrDefault();
Share:
10,455
black sensei
Author by

black sensei

Updated on June 27, 2022

Comments

  • black sensei
    black sensei almost 2 years

    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.

  • black sensei
    black sensei about 12 years
    i guess i would do different from zero then since RollNumber is long. is that ok?