Summary: in this tutorial, you will learn how to use the LINQ MinBy() method to find the element that has a minimum value based on a specified key selector function.
Introduction to the LINQ MinBy() method
The MinBy() method returns the minimum element in a sequence based on a specified key selector function.
Here’s the syntax of the MinBy() method:
TSource? MinBy<TSource,TKey> (
this IEnumerable<TSource> source,
Func<TSource,TKey> keySelector
);Code language: C# (cs)In this syntax:
TSourceis the type of element in thesourcesequence.TKeyis a type of key used to compare the elements in thesourcesequence.sourceis an input sequence of values.keySelectoris a function that extracts the key for each element.
The MinBy() method returns the element in the source sequence with the minimum key.
LINQ MinBy() method example
Suppose you have a Product class with three properties Name, Cost, and Price:
public class Product
{
public string Name
{
get; set;
}
public decimal Price
{
get; set;
}
public decimal Cost
{
get; set;
}
public Product(string name, decimal cost, decimal price)
{
Name = name;
Cost = cost;
Price = price;
}
public override string ToString() => $"{Name}, Cost:{Cost}, Price:{Price}";
}Code language: C# (cs)The following program uses the MinBy() method to find the product that has the lowest price:
using static System.Console;
var products = new List<Product>() {
new Product("A",100,120),
new Product("B",95,130),
new Product("C",140,150),
};
var product = products.MinBy(p => p.Price);
WriteLine(product);Code language: C# (cs)Output:
A, Cost:100, Price:120Code language: plaintext (plaintext)In this example, we use the following selector function to instruct the MinBy() method to return the product with the lowest price:
p => p.PriceCode language: C# (cs)To find the product with the lowest cost, you use the following selector function:
using static System.Console;
var products = new List<Product>() {
new Product("A",100,120),
new Product("B",95,130),
new Product("C",140,150),
};
var product = products.MinBy(p => p.Cost);
WriteLine(product);Code language: C# (cs)Output:
B, Cost:95, Price:130Code language: plaintext (plaintext)Summary
- Use the LINQ
MinBy()method to return the element in a sequence with the minimum key specified by a key selector function.