Reputation: 658
I have a breadcrumb table and I want to return the row that was most recently inserted. In SQL it would be a MAX()
function but not sure how to do the equivalent in LINQ. Basically I want to select the row that has the highest BreadCrumbID WHERE ProjectID = 49
.
Here's the query I have right now that would select all rows WHERE ProjectID = 49
. I want to select the row that has the highest BreadCrumbID
.
Thanks!
Code:
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var currentStatus = (from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49)
select new
{
Status = tbBreadCrumb.BreadCrumbID,
});
}
Upvotes: 1
Views: 32198
Reputation: 133
Try this, It will give 0 if there is no BreadCrumb in ProjectID=49 or give max BreadCrumbID
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var query=myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49);
var highestId = query.Any() ? query.Max(x => x.BreadCrumbID) : 0;
}
Upvotes: 1
Reputation: 11
Var highestId = myEntities.breadcrumbs.lastOrDefault(x=>x.ProjectId== 49)
Upvotes: 1
Reputation: 1214
You can use the Max()
linq extension method
var crum = myEntities.tbBreadCrumbs.Max(d=>d.breadcrumbId)
Upvotes: 1
Reputation: 754595
Try the following query
var currentStatus =
from x in myEntities.tbBreadCrumbs
where x.ProjectID == 49
orderby x.BreadCrumbID desc
select x.BreadCrumbID;
The first result in that query will be the highest BreadCrumbID
value where ProjectID
is 49
Upvotes: 3
Reputation: 28737
This query should get you the highest BreadCrumbId where ProjectID = 4
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var highestId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49)
.Max(x => x.BreadCrumbID);
}
Upvotes: 2
Reputation: 34238
try this:
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var currentStatus = (from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == myEntities.tbBreadCrumbs.Max(b=>b.ProjectId))
select new
{
Status = tbBreadCrumb.BreadCrumbID,
});
}
Upvotes: 4