C# 程序从列表中获取最小和最大元素

csharpprogrammingserver side programming更新于 2025/9/15 20:47:00

设置一个列表。

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

相关文章