LINQ
C#
.NET
programming
tutorial

How to use LINQ to select object with minimum or maximum property value

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Understanding LINQ for Selecting Objects with Minimum or Maximum Values

Language Integrated Query (LINQ) is a powerful feature of the .NET framework that provides an efficient and readable way to query data collections. A common task when working with collections is to find an object with the minimum or maximum value for a given property. Through this article, we’ll explore how LINQ simplifies this process with examples, technical explanations, and some subtopics to enhance your understanding.

Introduction to LINQ

LINQ allows .NET developers to write queries directly in C# (or other .NET languages) in a declarative way. It provides a rich set of methods that help filter, project, and manipulate collections in a concise and readable manner.

Selecting Objects with Minimum or Maximum Property Values

When working with collections, you may often need to find the object with the smallest or largest property value. LINQ provides several methods to do this, such as Min(), Max(), OrderBy(), OrderByDescending(), First(), and Last(). Let’s take a look at how to use these methods effectively.

Example Scenario

Consider a collection of Product objects, where each product has properties for Id, Name, and Price.

csharp
1public class Product
2{
3    public int Id { get; set; }
4    public string Name { get; set; }
5    public decimal Price { get; set; }
6}
7
8List<Product> products = new List<Product>
9{
10    new Product { Id = 1, Name = "Laptop", Price = 999.99m },
11    new Product { Id = 2, Name = "Smartphone", Price = 499.99m },
12    new Product { Id = 3, Name = "Tablet", Price = 299.99m }
13};

Finding the Minimum Priced Product

To find the product with the minimum price, use the Min() method in conjunction with First():

csharp
1var minPricedProduct = products
2    .OrderBy(p => p.Price)
3    .First();
4
5Console.WriteLine($"Product with the lowest price: {minPricedProduct.Name}, Price: {minPricedProduct.Price}");

Alternatively, using query syntax:

csharp
var minPricedProductQuery = (from p in products
                             orderby p.Price
                             select p).First();

Finding the Maximum Priced Product

To determine the product with the maximum price, apply the OrderByDescending() method:

csharp
1var maxPricedProduct = products
2    .OrderByDescending(p => p.Price)
3    .First();
4
5Console.WriteLine($"Product with the highest price: {maxPricedProduct.Name}, Price: {maxPricedProduct.Price}");

Alternatively, using query syntax:

csharp
var maxPricedProductQuery = (from p in products
                             orderby p.Price descending
                             select p).First();

Efficient Use with Aggregate Functions

If performance is a consideration and the collection is large, calculating Min() or Max() directly might be more efficient. This method computes the minimum or maximum value without sorting the collection:

csharp
decimal minPrice = products.Min(p => p.Price);
decimal maxPrice = products.Max(p => p.Price);

However, to select the whole object, you typically need to combine the result with a filter:

csharp
var cheapestProduct = products.First(p => p.Price == minPrice);
var priciestProduct = products.First(p => p.Price == maxPrice);

Summary Table

The following table summarizes the key LINQ methods and their purpose:

MethodPurposeExample Usage
OrderBy()Sorts in ascending orderOrderBy(p => p.Price).First()
OrderByDescending()Sorts in descending orderOrderByDescending(p => p.Price).First()
Min()Computes the minimum valueproducts.Min(p => p.Price)
Max()Computes the maximum valueproducts.Max(p => p.Price)
First()Retrieves the first elementFirst(p => p.Price == minPrice)
Last()Retrieves the last elementLast(p => p.Price == maxPrice)

Additional Considerations

  • Null Handling: Ensure the collection is not null before using LINQ operations to avoid exceptions.
  • Performance: When considering performance, remember that OrderBy() and OrderByDescending() sort the entire collection, which might not be ideal for large datasets.
  • Expression Trees: LINQ query expressions generate expression trees which can be inspected or executed differently, adding flexibility.

Conclusion

LINQ provides powerful, efficient, and readable methods for selecting objects based on their property values. By leveraging functions such as OrderBy, First, Min, and Max, developers can handle these common tasks with ease, enhancing code readability and maintainability. Understanding these methods and using them effectively will enable you to write better queries for your data collections.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms