C# 程序查找列表中的最大值、最小值、第二大和第二小的值
设定列表
var val = new int[] { 99, 35, 26, 87 };
现在获取最大值。
val.Max(z => z);
最小值
val.Min(z => z);
第二大值
val.OrderByDescending(z => z).Skip(1).First();
第二小值
val.OrderBy(z => z).Skip(1).First();
以下是代码 −
示例
using System; using System.Linq; public class Program { public static void Main() { var val = new int[] { 99, 35, 26, 87 }; var maxNum = val.Max(z => z); Console.WriteLine("Maximum Number: " + maxNum); var minNum = val.Min(z => z); Console.WriteLine("Minimum Number: " + minNum); var secondMax = val.OrderByDescending(z => z).Skip(1).First(); Console.WriteLine("Second Largest Number: " + secondMax); var secondMin = val.OrderBy(z => z).Skip(1).First(); Console.WriteLine("Second Smallest Number: " + secondMin); } }
输出结果
Maximum Number: 99 Minimum Number: 26 Second Largest Number: 87 Second Smallest Number: 35
广告