Enumerable.Max Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Retorna o valor máximo em uma sequência de valores.
Sobrecargas
| Nome | Description |
|---|---|
| Max(IEnumerable<Nullable<Single>>) |
Retorna o valor máximo em uma sequência de valores anuláveis Single . |
| Max(IEnumerable<Int32>) |
Retorna o valor máximo em uma sequência de Int32 valores. |
| Max(IEnumerable<Nullable<Int64>>) |
Retorna o valor máximo em uma sequência de valores anuláveis Int64 . |
| Max(IEnumerable<Single>) |
Retorna o valor máximo em uma sequência de Single valores. |
| Max(IEnumerable<Nullable<Int32>>) |
Retorna o valor máximo em uma sequência de valores anuláveis Int32 . |
| Max(IEnumerable<Decimal>) |
Retorna o valor máximo em uma sequência de Decimal valores. |
| Max(IEnumerable<Nullable<Decimal>>) |
Retorna o valor máximo em uma sequência de valores anuláveis Decimal . |
| Max(IEnumerable<Int64>) |
Retorna o valor máximo em uma sequência de Int64 valores. |
| Max(IEnumerable<Double>) |
Retorna o valor máximo em uma sequência de Double valores. |
| Max(IEnumerable<Nullable<Double>>) |
Retorna o valor máximo em uma sequência de valores anuláveis Double . |
| Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) |
Invoca uma função de transformação em cada elemento de uma sequência genérica e retorna o valor máximo resultante. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Single. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Single anulável. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Int64 anulável. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Int32 anulável. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Double anulável. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Int64. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Int32. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Double. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Decimal. |
| Max<TSource>(IEnumerable<TSource>) |
Retorna o valor máximo em uma sequência genérica. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Decimal anulável. |
Max(IEnumerable<Nullable<Single>>)
Retorna o valor máximo em uma sequência de valores anuláveis Single .
public:
[System::Runtime::CompilerServices::Extension]
static Nullable<float> Max(System::Collections::Generic::IEnumerable<Nullable<float>> ^ source);
public static float? Max(this System.Collections.Generic.IEnumerable<float?> source);
static member Max : seq<Nullable<single>> -> Nullable<single>
<Extension()>
Public Function Max (source As IEnumerable(Of Nullable(Of Single))) As Nullable(Of Single)
Parâmetros
- source
- IEnumerable<Nullable<Single>>
Uma sequência de valores anuláveis Single para determinar o valor máximo.
Retornos
Um valor do tipo Nullable<Single> em C# ou Nullable(Of Single) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source é null.
Comentários
O Max(IEnumerable<Nullable<Single>>) método usa a Single implementação para IComparable<T> comparar valores.
Se a sequência de origem estiver vazia ou contiver apenas valores, nullessa função retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Int32>)
Retorna o valor máximo em uma sequência de Int32 valores.
public:
[System::Runtime::CompilerServices::Extension]
static int Max(System::Collections::Generic::IEnumerable<int> ^ source);
public static int Max(this System.Collections.Generic.IEnumerable<int> source);
static member Max : seq<int> -> int
<Extension()>
Public Function Max (source As IEnumerable(Of Integer)) As Integer
Parâmetros
- source
- IEnumerable<Int32>
Uma sequência de valores da Int32 qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
source não contém elementos.
Comentários
O Max(IEnumerable<Int32>) método usa a Int32 implementação para IComparable<T> comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Nullable<Int64>>)
Retorna o valor máximo em uma sequência de valores anuláveis Int64 .
public:
[System::Runtime::CompilerServices::Extension]
static Nullable<long> Max(System::Collections::Generic::IEnumerable<Nullable<long>> ^ source);
public static long? Max(this System.Collections.Generic.IEnumerable<long?> source);
static member Max : seq<Nullable<int64>> -> Nullable<int64>
<Extension()>
Public Function Max (source As IEnumerable(Of Nullable(Of Long))) As Nullable(Of Long)
Parâmetros
- source
- IEnumerable<Nullable<Int64>>
Uma sequência de valores anuláveis Int64 para determinar o valor máximo.
Retornos
Um valor do tipo Nullable<Int64> em C# ou Nullable(Of Int64) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source é null.
Comentários
O Max(IEnumerable<Nullable<Int64>>) método usa a Int64 implementação para IComparable<T> comparar valores.
Se a sequência de origem estiver vazia ou contiver apenas valores, nullessa função retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Single>)
Retorna o valor máximo em uma sequência de Single valores.
public:
[System::Runtime::CompilerServices::Extension]
static float Max(System::Collections::Generic::IEnumerable<float> ^ source);
public static float Max(this System.Collections.Generic.IEnumerable<float> source);
static member Max : seq<single> -> single
<Extension()>
Public Function Max (source As IEnumerable(Of Single)) As Single
Parâmetros
- source
- IEnumerable<Single>
Uma sequência de valores da Single qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
source não contém elementos.
Comentários
O Max(IEnumerable<Single>) método usa a Single implementação para IComparable<T> comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Nullable<Int32>>)
Retorna o valor máximo em uma sequência de valores anuláveis Int32 .
public:
[System::Runtime::CompilerServices::Extension]
static Nullable<int> Max(System::Collections::Generic::IEnumerable<Nullable<int>> ^ source);
public static int? Max(this System.Collections.Generic.IEnumerable<int?> source);
static member Max : seq<Nullable<int>> -> Nullable<int>
<Extension()>
Public Function Max (source As IEnumerable(Of Nullable(Of Integer))) As Nullable(Of Integer)
Parâmetros
- source
- IEnumerable<Nullable<Int32>>
Uma sequência de valores anuláveis Int32 para determinar o valor máximo.
Retornos
Um valor do tipo Nullable<Int32> em C# ou Nullable(Of Int32) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source é null.
Comentários
O Max(IEnumerable<Nullable<Int32>>) método usa a Int32 implementação para IComparable<T> comparar valores.
Se a sequência de origem estiver vazia ou contiver apenas valores, nullessa função retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Decimal>)
Retorna o valor máximo em uma sequência de Decimal valores.
public:
[System::Runtime::CompilerServices::Extension]
static System::Decimal Max(System::Collections::Generic::IEnumerable<System::Decimal> ^ source);
public static decimal Max(this System.Collections.Generic.IEnumerable<decimal> source);
static member Max : seq<decimal> -> decimal
<Extension()>
Public Function Max (source As IEnumerable(Of Decimal)) As Decimal
Parâmetros
- source
- IEnumerable<Decimal>
Uma sequência de valores da Decimal qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
source não contém elementos.
Comentários
O Max(IEnumerable<Decimal>) método usa a Decimal implementação para IComparable<T> comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Nullable<Decimal>>)
Retorna o valor máximo em uma sequência de valores anuláveis Decimal .
public:
[System::Runtime::CompilerServices::Extension]
static Nullable<System::Decimal> Max(System::Collections::Generic::IEnumerable<Nullable<System::Decimal>> ^ source);
public static decimal? Max(this System.Collections.Generic.IEnumerable<decimal?> source);
static member Max : seq<Nullable<decimal>> -> Nullable<decimal>
<Extension()>
Public Function Max (source As IEnumerable(Of Nullable(Of Decimal))) As Nullable(Of Decimal)
Parâmetros
- source
- IEnumerable<Nullable<Decimal>>
Uma sequência de valores anuláveis Decimal para determinar o valor máximo.
Retornos
Um valor do tipo Nullable<Decimal> em C# ou Nullable(Of Decimal) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source é null.
Comentários
O Max(IEnumerable<Nullable<Decimal>>) método usa a Decimal implementação para IComparable<T> comparar valores.
Se a sequência de origem estiver vazia ou contiver apenas valores, nullessa função retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Int64>)
Retorna o valor máximo em uma sequência de Int64 valores.
public:
[System::Runtime::CompilerServices::Extension]
static long Max(System::Collections::Generic::IEnumerable<long> ^ source);
public static long Max(this System.Collections.Generic.IEnumerable<long> source);
static member Max : seq<int64> -> int64
<Extension()>
Public Function Max (source As IEnumerable(Of Long)) As Long
Parâmetros
- source
- IEnumerable<Int64>
Uma sequência de valores da Int64 qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max(IEnumerable<Int64>) para determinar o valor máximo em uma sequência.
List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };
long max = longs.Max();
Console.WriteLine("The largest number is {0}.", max);
/*
This code produces the following output:
The largest number is 4294967296.
*/
' Create a list of Long values.
Dim longs As New List(Of Long)(New Long() _
{4294967296L, 466855135L, 81125L})
' Get the maximum value in the list.
Dim max As Long = longs.Max()
' Display the result.
Console.WriteLine($"The largest number is {max}")
' This code produces the following output:
'
' The largest number is 4294967296
Comentários
O Max(IEnumerable<Int64>) método usa a Int64 implementação para IComparable<T> comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Double>)
Retorna o valor máximo em uma sequência de Double valores.
public:
[System::Runtime::CompilerServices::Extension]
static double Max(System::Collections::Generic::IEnumerable<double> ^ source);
public static double Max(this System.Collections.Generic.IEnumerable<double> source);
static member Max : seq<double> -> double
<Extension()>
Public Function Max (source As IEnumerable(Of Double)) As Double
Parâmetros
- source
- IEnumerable<Double>
Uma sequência de valores da Double qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
source não contém elementos.
Comentários
O Max(IEnumerable<Double>) método usa a Double implementação para IComparable<T> comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max(IEnumerable<Nullable<Double>>)
Retorna o valor máximo em uma sequência de valores anuláveis Double .
public:
[System::Runtime::CompilerServices::Extension]
static Nullable<double> Max(System::Collections::Generic::IEnumerable<Nullable<double>> ^ source);
public static double? Max(this System.Collections.Generic.IEnumerable<double?> source);
static member Max : seq<Nullable<double>> -> Nullable<double>
<Extension()>
Public Function Max (source As IEnumerable(Of Nullable(Of Double))) As Nullable(Of Double)
Parâmetros
- source
- IEnumerable<Nullable<Double>>
Uma sequência de valores anuláveis Double para determinar o valor máximo.
Retornos
Um valor do tipo Nullable<Double> em C# ou Nullable(Of Double) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max(IEnumerable<Nullable<Double>>) para determinar o valor máximo em uma sequência.
double?[] doubles = { null, 1.5E+104, 9E+103, -2E+103 };
double? max = doubles.Max();
Console.WriteLine("The largest number is {0}.", max);
/*
This code produces the following output:
The largest number is 1.5E+104.
*/
' Create an array of Nullable Double values.
Dim doubles() As Nullable(Of Double) =
{Nothing, 1.5E+104, 9.0E+103, -2.0E+103}
' Determine the maximum value in the array.
Dim max As Nullable(Of Double) = doubles.Max()
' Display the result.
Console.WriteLine($"The largest number is {max}")
' This code produces the following output:
'
' The largest number is 1.5E+104
Comentários
O Max(IEnumerable<Nullable<Double>>) método usa a Double implementação para IComparable<T> comparar valores.
Se a sequência de origem estiver vazia ou contiver apenas valores, nullessa função retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)
Invoca uma função de transformação em cada elemento de uma sequência genérica e retorna o valor máximo resultante.
public:
generic <typename TSource, typename TResult>
[System::Runtime::CompilerServices::Extension]
static TResult Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, TResult> ^ selector);
public static TResult Max<TSource,TResult>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TResult> selector);
static member Max : seq<'Source> * Func<'Source, 'Result> -> 'Result
<Extension()>
Public Function Max(Of TSource, TResult) (source As IEnumerable(Of TSource), selector As Func(Of TSource, TResult)) As TResult
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
- TResult
O tipo do valor retornado por selector.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
- selector
- Func<TSource,TResult>
Uma função de transformação a ser aplicada a cada elemento.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
Se o tipo TResult for implementado IComparable<T>, esse método usará essa implementação para comparar valores. Caso contrário, se o tipo TResult for implementado IComparable, essa implementação será usada para comparar valores.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- System.Linq.Enumerable.MaxBy
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Single.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static float Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, float> ^ selector);
public static float Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,float> selector);
static member Max : seq<'Source> * Func<'Source, single> -> single
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Single)) As Single
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>) método usa a Single implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se você fornecer uma função, selectorque projeta os membros de source um tipo numérico, especificamente Single.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Single anulável.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static Nullable<float> Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, Nullable<float>> ^ selector);
public static float? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,float?> selector);
static member Max : seq<'Source> * Func<'Source, Nullable<single>> -> Nullable<single>
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Nullable(Of Single))) As Nullable(Of Single)
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor que corresponde ao valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) método usa a Single implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se fornecer uma função, selector, que projeta os membros do source em um tipo numérico, especificamente Nullable<Single> em C# ou Nullable(Of Single) em Visual Basic.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Int64 anulável.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static Nullable<long> Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, Nullable<long>> ^ selector);
public static long? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,long?> selector);
static member Max : seq<'Source> * Func<'Source, Nullable<int64>> -> Nullable<int64>
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Nullable(Of Long))) As Nullable(Of Long)
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor que corresponde ao valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) método usa a Int64 implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se fornecer uma função, selector, que projeta os membros do source em um tipo numérico, especificamente Nullable<Int64> em C# ou Nullable(Of Int64) em Visual Basic.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Int32 anulável.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static Nullable<int> Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, Nullable<int>> ^ selector);
public static int? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int?> selector);
static member Max : seq<'Source> * Func<'Source, Nullable<int>> -> Nullable<int>
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Nullable(Of Integer))) As Nullable(Of Integer)
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor do tipo Nullable<Int32> em C# ou Nullable(Of Int32) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) método usa a Int32 implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se fornecer uma função, selector, que projeta os membros do source em um tipo numérico, especificamente Nullable<Int32> em C# ou Nullable(Of Int32) em Visual Basic.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Double anulável.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static Nullable<double> Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, Nullable<double>> ^ selector);
public static double? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,double?> selector);
static member Max : seq<'Source> * Func<'Source, Nullable<double>> -> Nullable<double>
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Nullable(Of Double))) As Nullable(Of Double)
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor do tipo Nullable<Double> em C# ou Nullable(Of Double) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) método usa a Double implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se fornecer uma função, selector, que projeta os membros do source em um tipo numérico, especificamente Nullable<Double> em C# ou Nullable(Of Double) em Visual Basic.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Int64.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static long Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, long> ^ selector);
public static long Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,long> selector);
static member Max : seq<'Source> * Func<'Source, int64> -> int64
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Long)) As Long
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) método usa a Int64 implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se você fornecer uma função, selectorque projeta os membros de source um tipo numérico, especificamente Int64.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Int32.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static int Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, int> ^ selector);
public static int Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int> selector);
static member Max : seq<'Source> * Func<'Source, int> -> int
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Integer)) As Integer
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) método usa a Int32 implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se você fornecer uma função, selectorque projeta os membros de source um tipo numérico, especificamente Int32.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Double.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static double Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, double> ^ selector);
public static double Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,double> selector);
static member Max : seq<'Source> * Func<'Source, double> -> double
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Double)) As Double
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>) método usa a Double implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se você fornecer uma função, selectorque projeta os membros de source um tipo numérico, especificamente Double.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo Decimal.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static System::Decimal Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, System::Decimal> ^ selector);
public static decimal Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,decimal> selector);
static member Max : seq<'Source> * Func<'Source, decimal> -> decimal
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Decimal)) As Decimal
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source ou selector é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) método usa a Decimal implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se você fornecer uma função, selectorque projeta os membros de source um tipo numérico, especificamente Decimal.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>)
Retorna o valor máximo em uma sequência genérica.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource Max(System::Collections::Generic::IEnumerable<TSource> ^ source);
public static TSource Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source);
static member Max : seq<'Source> -> 'Source
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource)) As TSource
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Retornos
O valor máximo na sequência.
Exceções
source é null.
Nenhum objeto em source implementa a interface ou IComparable a IComparable<T> interface.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>) para determinar o valor máximo em uma sequência de IComparable<T> objetos.
/// <summary>
/// This class implements IComparable to be able to
/// compare one Pet to another Pet.
/// </summary>
class Pet : IComparable<Pet>
{
public string Name { get; set; }
public int Age { get; set; }
/// <summary>
/// Compares this Pet to another Pet by
/// summing each Pet's age and name length.
/// </summary>
/// <param name="other">The Pet to compare this Pet to.</param>
/// <returns>-1 if this Pet is 'less' than the other Pet,
/// 0 if they are equal,
/// or 1 if this Pet is 'greater' than the other Pet.</returns>
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;
}
}
public static void MaxEx3()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
Pet max = pets.Max();
Console.WriteLine(
"The 'maximum' animal is {0}.",
max.Name);
}
/*
This code produces the following output:
The 'maximum' animal is Barley.
*/
' This class implements IComparable
' and has a custom 'CompareTo' implementation.
Class Pet
Implements IComparable(Of Pet)
Public Name As String
Public Age As Integer
''' <summary>
''' Compares Pet objects by the sum of their age and name length.
''' </summary>
''' <param name="other">The Pet to compare this Pet to.</param>
''' <returns>-1 if this Pet's sum is 'less' than the other Pet,
''' 0 if they are equal,
''' or 1 if this Pet's sum is 'greater' than the other Pet.</returns>
Function CompareTo(ByVal other As Pet) As Integer _
Implements IComparable(Of Pet).CompareTo
If (other.Age + other.Name.Length > Me.Age + Me.Name.Length) Then
Return -1
ElseIf (other.Age + other.Name.Length = Me.Age + Me.Name.Length) Then
Return 0
Else
Return 1
End If
End Function
End Class
Sub MaxEx3()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Find the "maximum" pet according to the
' custom CompareTo() implementation.
Dim max As Pet = pets.Max()
' Display the result.
Console.WriteLine($"The 'maximum' animal is {max.Name}")
End Sub
' This code produces the following output:
'
' The 'maximum' animal is Barley
Comentários
Se o tipo TSource for implementado IComparable<T>, o Max<TSource>(IEnumerable<TSource>) método usará essa implementação para comparar valores. Caso contrário, se o tipo TSource for implementado IComparable, essa implementação será usada para comparar valores.
Se TSource for um tipo de referência e a sequência de origem estiver vazia ou contiver apenas valores, nullesse método retornará null.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)
Aplica-se a
Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)
Invoca uma função de transformação em cada elemento de uma sequência e retorna o valor máximo de Decimal anulável.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static Nullable<System::Decimal> Max(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, Nullable<System::Decimal>> ^ selector);
public static decimal? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,decimal?> selector);
static member Max : seq<'Source> * Func<'Source, Nullable<decimal>> -> Nullable<decimal>
<Extension()>
Public Function Max(Of TSource) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Nullable(Of Decimal))) As Nullable(Of Decimal)
Parâmetros de tipo
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IEnumerable<TSource>
Uma sequência de valores da qual determinar o valor máximo.
Uma função de transformação a ser aplicada a cada elemento.
Retornos
O valor do tipo Nullable<Decimal> em C# ou Nullable(Of Decimal) em Visual Basic que corresponde ao valor máximo na sequência.
Exceções
source ou selector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) para determinar o valor máximo em uma sequência de valores projetados.
Note
Este exemplo de código usa uma sobrecarga do método diferente da sobrecarga específica que este artigo descreve. Para estender o exemplo para a sobrecarga que este artigo descreve, altere o corpo da selector função.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age + pet.Name.Length);
Console.WriteLine(
"The maximum pet age plus name length is {0}.",
max);
}
/*
This code produces the following output:
The maximum pet age plus name length is 14.
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub MaxEx4()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Determine the "maximum" pet by passing a
' lambda expression to Max() that sums the pet's age
' and name length.
Dim max As Integer = pets.Max(Function(pet) _
pet.Age + pet.Name.Length)
' Display the result.
Console.WriteLine($"The maximum pet age plus name length is {max}")
End Sub
' This code produces the following output:
'
' The maximum pet age plus name length is 14
Comentários
O Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) método usa a Decimal implementação para IComparable<T> comparar valores.
Você pode aplicar esse método a uma sequência de valores arbitrários se fornecer uma função, selector, que projeta os membros do source em um tipo numérico, especificamente Nullable<Decimal> em C# ou Nullable(Of Decimal) em Visual Basic.
Em Visual Basic sintaxe de expressão de consulta, uma cláusula Aggregate Into Max() se traduz em uma invocação de Max.
Confira também
- cláusula Aggregate (Visual Basic)