ใช้เมธอด LINQ Min() และ Max() เพื่อหาค่าต่ำสุดและสูงสุดจากลำดับตัวเลข
ตัวอย่างโค้ด
using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
static void Main()
{
List list = new List { 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("ค่าน้อยที่สุด = {0}", min_num);
Console.WriteLine("ค่ามากที่สุด = {0}", max_num);
}
}
ผลลัพธ์
150 300 400 350 450 550 600 ค่าน้อยที่สุด = 150 ค่ามากที่สุด = 600
หมายเหตุ: Min/Max ทำงานกับชนิดข้อมูลที่ implement IComparable ได้ (ตัวเลข, string, DateTime เป็นต้น)