user1431633
user1431633

Reputation: 658

C# Using LINQ to select max ID of row

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

Answers (6)

Mayur Dongre
Mayur Dongre

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

MoZahid
MoZahid

Reputation: 11

Var highestId = myEntities.breadcrumbs.lastOrDefault(x=>x.ProjectId== 49)

Upvotes: 1

Wesley Skeen
Wesley Skeen

Reputation: 1214

You can use the Max() linq extension method

var crum = myEntities.tbBreadCrumbs.Max(d=>d.breadcrumbId)

Upvotes: 1

JaredPar
JaredPar

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

Kenneth
Kenneth

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

undefined
undefined

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

Related Questions