Home / Programming / Blog article: Select Max Value With LINQ To SQL

| RSS

Select Max Value With LINQ To SQL

July 7th, 2009 | 2 Comments | Posted in Programming

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..

Leave a Reply 10787 views, 2 so far today |
Tags: ,
Follow Discussion

2 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.

Leave a Reply





Switch to our mobile site