Max()方法返回集合中最大的数值元素。
下面的示例演示原始集合上的Max()方法。
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };
var largest = intList.Max();
Console.WriteLine("最大元素: {0}", largest);
var largestEvenElements = intList.Max(i => {
if(i%2 == 0)
return i;
return 0;
});
Console.WriteLine("最大偶数: {0}", largestEvenElements );最大元素:87 最大偶数:50
下面的示例演示复杂类型集合上的Max()方法。
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
var oldest = studentList.Max(s => s.Age);
Console.WriteLine("Oldest Student Age: {0}", oldest);Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim oldest = studentList.Max(Function(s) s.Age)
Console.WriteLine("最大的学生年龄: {0}", oldest)最大的学生年龄:21
Max返回任何数据类型的结果。以下示例显示了如何找到集合中 名称最长 的学生:
public class Student : IComparable<Student>
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public int StandardID { get; set; }
public int CompareTo(Student other)
{
if (this.StudentName.Length >= other.StudentName.Length)
return 1;
return 0;
}
}
class Program
{
static void Main(string[] args)
{
// 学生集合
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Steve" , Age = 15 }
};
var studentWithLongName = studentList.Max();
Console.WriteLine("Student ID: {0}, Student Name: {1}",
.StudentID, studentWithLongName.StudentName)
}
}Student ID:5,StudentName :Steve
您可以使用与Max相同的方式使用Min扩展方法/运算符。
根据上面的实例,要找到名字最长的学生,需要实现IComparable<T>接口,并在CompareTo方法中比较学生名字的长度。现在,您可以使用Max()方法,它将使用CompareTo方法来返回适当的结果。
C#查询语法不支持Max运算符。但是,它在VB.Net版查询语法如下所示。
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim maxAge = Aggregate st In studentList Into Max(st.Age)
Console.WriteLine("最大学生年龄: {0}", maxAge);最大学生年龄:21
在下一部分中了解另一个聚合运算符-Sum。