I have searched on stack overflow, but find example for max ID only , I want to find Max ID for some particular condition. Something like this
var nRow = from p in ctx.FormControls
. where p.FormObjectsId == FormID
. select Max(p.Id);
How to do it ?
Well if you really like query expressions, you can express the "filter and projection" and then use the Max
extension method:
var query = from p in ctx.FormControls
where p.FormObjectsId == FormID
select p.ID;
var maxID = query.Max();
You can do this without the intermediate variable if you want, but I find query expressions get ugly when you need to put them in brackets etc.
I would personally use the overload of Max
that allows you to specify the projection inline, however... and at that point, there's no benefit using the query expression form - just use the extension methods and lambda expressions all the way:
var maxID = ctx.FormControls
.Where(p => p.FormObjectsId == FormID)
.Max(p => p.ID);
Don't forget that all of this uses deferred execution up until the Max
call (which uses immediate execution) - so for example, if this is executing against LINQ to SQL or the Entity Framework, the whole query will be converted to SQL.
See more on this question at Stackoverflow