Max(TSource) 方法 (IEnumerable(TSource))
 此文章由机器翻译。 将光标移到文章的句子上，以查看原文。 更多信息。 译文 原文

# Enumerable.Max<TSource> 方法 (IEnumerable<TSource>)

.NET Framework 4.6 and 4.5

## 语法

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

source

Type: TSource

TSource

source 中的元素的类型。

## 异常

Exception Condition
ArgumentNullException

sourcenull

## 示例

```/// <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.
*/

```

## 版本信息

Universal Windows Platform
4.5 后可用
.NET Framework
3.5 后可用
Portable Class Library

Silverlight
2.0 后可用
Windows Phone Silverlight
7.0 后可用
Windows Phone
8.1 后可用

© 2015 Microsoft