我有一个包含多个元素的List<int>
。 我知道如果使用foreach
遍历它,可以获取所有值,但我只需要列表中的最大整数值。
var l = new List<int>() { 1, 3, 2 };
我有一个包含多个元素的List<int>
。 我知道如果使用foreach
遍历它,可以获取所有值,但我只需要列表中的最大整数值。
var l = new List<int>() { 1, 3, 2 };
假设使用的是.NET Framework 3.5或更高版本:
var l = new List<int>() { 1, 3, 2 };
var max = l.Max();
Console.WriteLine(max); // prints 3
在Enumerable类中有很多很酷的时间节省者,就像这些一样。
使用 Enumerable.Max
int max = l.Max();
int max = (from l in list select l).Max().FirstOrDefault();
l.Max();
您可以使用这个语法:
l.OrderByDescending(x => x).First(); //for maximum
l.OrderBy(x => x).First(); // for minimum
或者您可以使用LINQ中的Max()和Min()方法。
我希望我所说的会对您有所帮助......
using System.Linq;
using System.Collections.Generic;
int Max = list.Max();
int max = listOfInts[0];
for(int i = 1; i < listOfInts.Count; i++) {
max = Math.Max(max, listOfInts[i]);
}
如果您不想使用Linq:
l.Sort();
int min = l[0]; //1
int max = l[l.Count - 1]; //3
l
是一个可枚举列表,否则它不会编译通过。此外,(from l in list select l)
也没有意义。 - Yuriy Faktorovich