[LINQ Operators] Max

The “Max” operator finds the maximum value of a sequence.

 

1. Sample Data Objects

To test examples, you need to include the <data classes> in your project.

 

2. “Max” operator

  • NonDeferred operator
  • Purpose: Aggregate

 

3. Prototypes

public static NUMERICTYPE Max(
this IEnumerable<NUMERICTYPE> source)

public static Nullable<NUMERICTYPE> Max(
  this IEnumerable<Nullable<NUMERICTYPE>> source)

public static NUMERICTYPE Max(
  this IEnumerable<T> source,
  Func<T, NUMERICTYPE> selector)

public static Nullable<NUMERICTYPE> Max<T>(
  this IEnumerable<T> source,
  Func<T, Nullable<NUMERICTYPE>> selector)

The “NUMERICTYPE” can be int, long, double, or decimal. There are many overloaded “Max()” operators but they do the same thing: returns the maximum one of numeric values .

Unlike the “Sum()” operator, the “Max()” does not need to be used just for number types, (for example, strings can be compared).

public static S Max<T, S>(
  this IEnumerable<T> source,
  Func<T, S> selector)

You can choose what can be returned.

 

4. Example 1 (Standard Operator)

int[] nums = new int[] { 3, 9, 1, 2, 10, 4, 8, 7, 6, 5 };

int maxNum = nums.Max();
Console.WriteLine("The max between 1 to 10: {0}", maxNum); // 10

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Max()” operator.

 

6. Example 3 (Standard Operator) – with a selector

IEnumerable<Food> foods = Food.GetFoods();

decimal maxPrice = foods.Max(f => f.Price ?? 0M);
Console.WriteLine("The max price: {0}", maxPrice); // 8.99

 

The “Max()” treats the null values like this:

  • Null is ignored when non-null values exist in the collection
  • Returns null if the collection is empty or contains only nulls
IEnumerable<Food> foods = Food.GetFoods();

decimal? maxPrice = foods.Max(f => f.Price);
Console.WriteLine("The max price: {0}", maxPrice ?? 0); // 8.99

 

7. Example 4 (Standard Operator) – non-numeric return value

It is not a good idea to use “Max()” with non-numeric values without a custom comparer. The result can be non-intuitive. If you are curious, look at the following example.

IEnumerable<Food> foods = Food.GetFoods();

string foodName = foods.Max(f => f.Name);
Console.WriteLine("The Last Food Name: {0}", foodName); // Special

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s