C#程序从列表中获取最小和最大元素
设定列表。
List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };要获得最小的元素,请使用Min()方法。
list.AsQueryable().Min();
要获得最大的元素,请使用Max()方法。
list.AsQueryable().Max();
让我们看完整的代码-
示例
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
foreach(long ele in list){
Console.WriteLine(ele);
}
//得到最大的元素
long max_num = list.AsQueryable().Max();
//最小元素
long min_num = list.AsQueryable().Min();
Console.WriteLine("Smallest number = {0}", min_num);
Console.WriteLine("Largest number = {0}", max_num);
}
}输出结果
150 300 400 350 450 550 600 Smallest number = 150 Largest number = 600