C# Enumerable Max(IEnumerable, Func)

Description

Invokes a transform function on each element of a sequence and returns the maximum Int64 value.

Syntax


public static long Max<TSource>(
  this IEnumerable<TSource> source,
  Func<TSource, long> selector
)

Parameters

  • TSource - The type of the elements of source.
  • source - A sequence of values to determine the maximum value of.
  • selector - A transform function to apply to each element.

Returns

returns The maximum value in the sequence.

Example

The following code example demonstrates how to use Max to determine the maximum value in a sequence of projected values.


//w w  w.  j  a v  a 2s . 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 } };

    int max = pets.Max(pet => pet.Age + pet.Name.Length);

    Console.WriteLine(max);
  }
}
    
class Pet{
    public string Name { get; set; }
    public int Age { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable