Reputation: 125
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 ?
Upvotes: 1
Views: 13498
Reputation: 1500215
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.
Upvotes: 2
Reputation: 148524
Query syntax :
var nRow = (from p in ctx.FormControls where p.FormObjectsId == FormID select p.Id).Max();
Upvotes: 0
Reputation: 5250
Just order by ID Descending, that would by nature get you the max ID.
var nRow = (from p in ctx.FormControls
where p.FormObjectsId == FormID
select p.ID).OrderByDescending(x => x.p.ID);
Upvotes: 0
Reputation: 223237
You can do that like:
var max = ctx.FormControls.Where(r => r.FormObjectsID == FormID)
.Max(r => r.Id);
With your query expression you can do:
var nRow = (from p in ctx.FormControls
where p.FormObjectsId == FormID
select p.Id).Max();
Upvotes: 7
Reputation: 157
something.Where(t => t.something> 0).Max(w => w.other);
or even Max of where
Upvotes: 1