CSharp - LINQ Max

Introduction

The Max operator returns the maximum value of an input sequence.

Prototypes

There are four prototypes we cover. The First Max Prototype

public static Numeric Max(
   this IEnumerable<Numeric> source);

The Numeric type must be one of int, long, double, or decimal or one of their nullable equivalents, int?, long?, double?, or decimal?.

The first prototype of the Max operator returns the element with the maximum numeric value in the source sequence.

If the element type implements the IComparable<T> interface, that interface will be used to compare the elements.

If the elements do not implement the IComparable<T> interface, the nongeneric IComparable interface will be used.

An empty sequence, or one that contains only null values, will return the value of null.

The second prototype of the Max operator behaves like the previous, except it is for non-Numeric types.

public static T Max<T>(
   this IEnumerable<T> source);

The third prototype is for Numeric types with a selector method delegate.

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

The fourth prototype is for non-Numeric types with a selector method.

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

Exceptions

  • ArgumentNullException is thrown if any argument is null.
  • InvalidOperationException is thrown if the source sequence is empty for the Numeric versions of the prototypes if the type T is non-nullable. If the types are nullable, such as int?, long?, double?, or decimal?, a null is returned from the operator instead.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program// w ww . jav  a 2s. co  m
{
    static void Main(string[] args)
    {
        int[] myInts = new int[] { 974, 2, 7, 1374, 27, 54 };
        int maxInt = myInts.Max();
        Console.WriteLine(maxInt);
    }
}

Result

Related Topics