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
广告