locked
Return query from Linq as Int RRS feed

  • Question

  • User-259260637 posted

    I am trying to think of a better way top return an int from the below query.

    var id = 0;
            if (hashCheck == hash)
            {
                using (var db = new DbDataContext())
                {
                    var q = db.tblRevisions.OrderByDescending(x => x.RevisionId == revisionId);
    
                    id = q.FirstOrDefault().RevisionId; // Could be null with no check
                }
            }
            return id;

    I wondered if this was the right way to return to a variable? 

    Friday, July 24, 2015 9:18 AM

Answers

  • User2024324573 posted

    var q = db.tblRevisions.OrderByDescending(x => x.RevisionId == revisionId);

    id = q.FirstOrDefault().RevisionId; // Could be null with no check

    try to use

    var q = db.tblRevisions.where(x=>x.RevisionId==revisionId).OrderByDescending(x => x.RevisionId == revisionId).ToList(); //if you have multiple values
    if(q!=null)
    {
    id = q.Select(s=>s.RevisionId).FirstOrDefault();
    }

    Hope this will help.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 24, 2015 3:08 PM
  • User-84896714 posted

    Hi StudentRik,

    var q = db.tblRevisions.OrderByDescending(x => x.RevisionId == revisionId);

    What is revisionId? Why do you use that?
    Assume you want to get the max RevisionId, you could use below code.

    using (var db = new DbDataContext())
    {
        var q = db.tblRevisions.OrderByDescending(x => x.RevisionId).FirstOrDefault();
        if (q != null)
        {
            id = q.RevisionId;
        }
    }

    Best Regards,
    Wang Li

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2015 2:13 AM

All replies

  • User2024324573 posted

    var q = db.tblRevisions.OrderByDescending(x => x.RevisionId == revisionId);

    id = q.FirstOrDefault().RevisionId; // Could be null with no check

    try to use

    var q = db.tblRevisions.where(x=>x.RevisionId==revisionId).OrderByDescending(x => x.RevisionId == revisionId).ToList(); //if you have multiple values
    if(q!=null)
    {
    id = q.Select(s=>s.RevisionId).FirstOrDefault();
    }

    Hope this will help.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 24, 2015 3:08 PM
  • User-84896714 posted

    Hi StudentRik,

    var q = db.tblRevisions.OrderByDescending(x => x.RevisionId == revisionId);

    What is revisionId? Why do you use that?
    Assume you want to get the max RevisionId, you could use below code.

    using (var db = new DbDataContext())
    {
        var q = db.tblRevisions.OrderByDescending(x => x.RevisionId).FirstOrDefault();
        if (q != null)
        {
            id = q.RevisionId;
        }
    }

    Best Regards,
    Wang Li

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2015 2:13 AM