Select Max Value in linq to entities

asp.net-mvc-3 entity-framework linq

Question

I am trying to select MAX LevelId value for a user and then assign that value to a variable.

In plain SQL the equivalent is:

SELECT        MAX(LevelID) AS MaxLevel
FROM            Character
WHERE        (UserId = 'John')


//Check User existing Characters max level per user

int UserLevelID = 0;

var userQuery = (from o in db.Characters
where o.UserId == UserID
      select o);

UserLevelID = userQuery.Max(LevelID);

Here lies the problem. I don't know how to extract the max value of levelID

1
3
7/6/2012 4:11:34 PM

Accepted Answer

You can do it all in one query:

var userLevelId = db.Characters.Where(o => o.UserID == UserID)
                               .Max(o => o.LevelID);

I've changed it away from being a query expression because that was introducing more cruft - use query expressions where they actually help readability, and extension method calls for simple solutions where they're more readable.

9
7/6/2012 4:13:57 PM

Popular Answer

How about:

var theLevel = db.Characters.Where(z => z.UserId == UserID).Max(z => z.LevelID);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow