Today I was asked a question by a developer on my team. The question is “How do you select MAX value for a column in a table with LINQ To SQL?”. I will try to answer the question in this post with an example. Let’s say that we want to retrieve maximum unit price from Products table in Northwind database. In T-SQL such a query can be written like this.

SELECT MAX(UnitPrice)
FROM products

 

Query above produces the correct result.

image

In LINQ To SQL we can write the following query

(from p in Products select (p.UnitPrice)).Max()  

 

which will get translated into this T-SQL.

 image

Other than MAX we can also use other aggregates such as MIN, SUM etc..

Tagged with:
 

12 Responses to Select Max Value With LINQ To SQL

  1. Shirley says:

    I a trying to write the following query in linq, t_sql

    select colId,
    colTaskType,
    MaxID
    from tblTaskType
    join (
    select tblCheckList.colTaskTypeID,
    max(colItemNumber) MaxID
    from tblCheckList
    group by colTaskTypeID
    ) x on coltaskTypeID = tblTaskType.colID

    Please help..

  2. Deepak says:

    Hi Shirley,

    Can you please post your create table statements? I’ll then be able to help you out.

  3. james says:

    Exception raised:
    The method ‘Max’ is not supported.

    public int GetLastPrintCheckID()
    {
    try
    {
    var printCheck = (from o in _context.PrintChecks
    select o.PrintCheckID).Max();
    return printCheck;
    }
    catch (Exception exx)
    {
    return 0;
    }
    }

  4. james says:

    With the above exception, the workaround was as follows:

    var query = _context.Execute(new Uri(string.Format(“{0}/PrintChecks?$orderby=PrintCheckID desc&$top=1&$select=PrintCheckID”, _context.BaseUri), UriKind.RelativeOrAbsolute));

    var printCheck = query.FirstOrDefault();

  5. Deepak says:

    James,

    Max is supported in LINQ To SQL queries. I ran the query you posted on a sample database and it worked.

  6. Nice tip, I used not to use LINQ in my code wherever I can, but I think that there’re times when you MUST use it. Selecting max values for me without T-SQL means to iterate through all the rows to get the max value. :(

    Thanks for your help! :)

  7. Filipe Colaço says:

    Solution:

    var q = (from data in db.Tickets.Where(p => (p.DataInsercao).Year == System.DateTime.Now.Year).OrderByDescending(p => p.Ticket)
    select data).Take(1);

    foreach (var v in q)
    {
    //Response.Write(v.Ticket.ToString());
    LabelTicket.Text = v.Ticket.ToString();

    }

  8. Filipe Colaço says:

    Sorry:

    var q = (from data in db.Tickets.Where(p => (p.DataInsercao).Year == System.DateTime.Now.Year).OrderByDescending(p => p.Ticket)
    select new {data.Ticket }).Take(1);

    foreach (var v in q)
    {
    LabelTicket.Text = (v.Ticket).ToString();
    }

  9. el Khatib says:

    Thanks you so much :)

  10. Deepak says:

    Most welcome el Khatib.

  11. KCuncle says:

    thk for sample

  12. manesti says:

    Thank you very much

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>