Find the Minimum Value in a Numeric Sequence

Use the Min operator to return the minimum value from a sequence of numeric values.

Example 1

The following example finds the lowest unit price of any product.

If you run this query against the Northwind sample database, the output is: 2.5000.

System.Nullable<Decimal> lowestUnitPrice =
    (from prod in db.Products
    select prod.UnitPrice)
    .Min();

Console.WriteLine(lowestUnitPrice);
Dim lowestUnitPrice = Aggregate prod In db.Products _
                      Into Min(prod.UnitPrice)

Console.WriteLine(lowestUnitPrice)

Example 2

The following example finds the lowest freight amount for any order.

If you run this query against the Northwind sample database, the output is: 0.0200.

System.Nullable<Decimal> lowestFreight =
    (from ord in db.Orders
    select ord.Freight)
    .Min();

Console.WriteLine(lowestFreight);
Dim lowestFreight = Aggregate ord In db.Orders _
                    Into Min(ord.Freight)

Console.WriteLine(lowestFreight)

Example 3

The following example uses Min to find the Products that have the lowest unit price in each category. The output is arranged by category.

var minQuery =
    from prod in db.Products
    group prod by prod.CategoryID into grouping
    select new
    {
        grouping.Key,
        LeastExpensiveProducts =
            from prod2 in grouping
            where prod2.UnitPrice == grouping.Min(prod3 =>
            prod3.UnitPrice)
            select prod2
    };

foreach (var grp in minQuery)
{
    Console.WriteLine(grp.Key);
    foreach (var listing in grp.LeastExpensiveProducts)
    {
        Console.WriteLine(listing.ProductName);
    }
}
Dim minQuery = From prod In db.Products() _
               Group prod By prod.CategoryID Into grouping = Group _
               Select CategoryID, LeastExpensiveProducts = _
                   From prod2 In grouping _
                   Where prod2.UnitPrice = grouping.Min(Function(prod3) _
                   prod3.UnitPrice)

For Each grp In minQuery
    Console.WriteLine(grp.CategoryID)
    For Each listing In grp.LeastExpensiveProducts
        Console.WriteLine(listing.ProductName)
    Next
Next

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

1

Guaraná Fantástica

2

Aniseed Syrup

3

Teatime Chocolate Biscuits

4

Geitost

5

Filo Mix

6

Tourtière

7

Longlife Tofu

8

Konbu

See also