C# Enumerable Max(IEnumerable)

Description

Returns the maximum value in a generic sequence.

Syntax


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

Parameters

  • TSource - The type of the elements of source.
  • source - A sequence of values to determine the maximum value of.

Example

The following code example demonstrates how to use Max(IEnumerable) to determine the maximum value in a sequence of IComparable objects.


//  w w  w.jav  a2s. c o  m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    Pet[] pets = { new Pet { Name="a", Age=8 },
                   new Pet { Name="b", Age=4 },
                   new Pet { Name="c", Age=1 } };

    Pet max = pets.Max();

    Console.WriteLine(max.Name);

  }
}
    
class Pet : IComparable<Pet>
{
    public string Name { get; set; }
    public int Age { get; set; }
    int IComparable<Pet>.CompareTo(Pet other)
    {
        int sumOther = other.Age + other.Name.Length;
        int sumThis = this.Age + this.Name.Length;

        if (sumOther > sumThis)
            return -1;
        else if (sumOther == sumThis)
            return 0;
        else 
            return 1;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable