Share via


How to: Find the Maximum Value in a Numeric Sequence (LINQ to SQL)

Use the Max operator to find the highest value in a sequence of numeric values.

Example

The following example finds the latest date of hire for any employee.

If you run this query against the sample Northwind database, the output is: 11/15/1994 12:00:00 AM.

Dim latestHireDate = Aggregate emp In db.Employees _
                     Into Max(emp.HireDate)

Console.WriteLine(latestHireDate)
System.Nullable<DateTime> latestHireDate =
    (from emp in db.Employees
    select emp.HireDate)
    .Max();

Console.WriteLine(latestHireDate);

The following example finds the most units in stock for any product.

If you run this example against the sample Northwind database, the output is: 125.

Dim maxUnitsInStock = Aggregate prod In db.Products _
                      Into Max(prod.UnitsInStock)

Console.WriteLine(maxUnitsInStock)
System.Nullable<Int16> maxUnitsInStock =
    (from prod in db.Products
    select prod.UnitsInStock)
    .Max();

Console.WriteLine(maxUnitsInStock);

The following example uses Max to find the Products that have the highest unit price in each category. The output then lists the results by category.

Dim maxQuery = From prod In db.Products() _
    Group prod By prod.CategoryID Into grouping = Group _
    Select CategoryID, _
    MostExpensiveProducts = _
        (From prod2 In grouping _
        Where prod2.UnitPrice = _
        grouping.Max(Function(prod3) prod3.UnitPrice))

For Each grp In maxQuery
    Console.WriteLine(grp.CategoryID)
    For Each listing In grp.MostExpensiveProducts
        Console.WriteLine(listing.ProductName)
    Next
Next
var maxQuery =
    from prod in db.Products
    group prod by prod.CategoryID into grouping
    select new
    {
        grouping.Key,
        MostExpensiveProducts =
            from prod2 in grouping
            where prod2.UnitPrice == grouping.Max(prod3 =>
                prod3.UnitPrice)
            select prod2
    };

foreach (var grp in maxQuery)
{
    Console.WriteLine(grp.Key);
    foreach (var listing in grp.MostExpensiveProducts)
    {
        Console.WriteLine(listing.ProductName);
    }
}

If you run the previous query against the Northwind sample database, your results will resemble the following:

1

Côte de Blaye

2

Vegie-spread

3

Sir Rodney's Marmalade

4

Raclette Courdavault

5

Gnocchi di nonna Alice

6

Thüringer Rostbratwurst

7

Manjimup Dried Apples

8

Carnarvon Tigers

See Also

Concepts

Downloading Sample Databases (LINQ to SQL)

Other Resources

Aggregate Queries (LINQ to SQL)