Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การหาค่าน้อยที่สุดในอาร์เรย์ C# ด้วยเมธอด Min()

เมธอด Min() ใน System.Linq ใช้หาค่าต่ำสุด (Minimum) จากลำดับข้อมูลตัวเลข ทำงานได้กับอาร์เรย์ ลิสต์ และ IEnumerable ทุกชนิด

รูปแบบการใช้งาน

int[] arr = { 5, 9, 2, 7 };
int min = arr.Min(); // 2

โค้ดตัวอย่างสมบูรณ์

using System;
using System.Linq;

class Demo
{
    static void Main()
    {
        int[] arr = { 5, 9, 2, 7 };
        
        Console.WriteLine("อาร์เรย์: " + string.Join(", ", arr));
        Console.WriteLine($"ค่าน้อยที่สุด: {arr.Min()}"); // 2
        
        // ตัวอย่างเพิ่มเติม
        double[] prices = { 19.99, 9.50, 29.99, 5.00, 14.95 };
        Console.WriteLine($"\nราคาต่ำสุด: {prices.Min():C}"); // $5.00
        
        string[] words = { "apple", "banana", "cat", "dog" };
        Console.WriteLine($"คำสั้นที่สุด: {words.Min(w => w.Length)} ตัวอักษร"); // 3
        
        // กับออบเจกต์
        var products = new[]
        {
            new { Name = "A", Price = 100 },
            new { Name = "B", Price = 50 },
            new { Name = "C", Price = 200 }
        };
        Console.WriteLine($"สินค้าราคาต่ำสุด: {products.Min(p => p.Price)}"); // 50
    }
}

ผลลัพธ์

อาร์เรย์: 5, 9, 2, 7
ค่าน้อยที่สุด: 2

ราคาต่ำสุด: $5.00
คำสั้นที่สุด: 3 ตัวอักษร
สินค้าราคาต่ำสุด: 50

เมธอด Min() แบบต่างๆ

รูปแบบคำอธิบาย
Min()หาค่าน้อยที่สุดของตัวเลขโดยตรง
Min(selector)เลือกคุณสมบัติ/คำนวณค่า แล้วหาค่าน้อยที่สุด
MinBy(selector)คืน องค์ประกอบทั้งตัว ที่มีค่าน้อยที่สุด (.NET 6+)

ตัวอย่าง MinBy (.NET 6+)

var cheapest = products.MinBy(p => p.Price);
// cheapest = { Name = "B", Price = 50 }

ข้อควรระวัง

  • หากลำดับว่างเปล่า จะโยน InvalidOperationException
  • ใช้ DefaultIfEmpty() หรือตรวจสอบ Any() ก่อนเรียก
  • สำหรับ Nullable types (int?, double?) จะคืนค่า null หากทุกค่าเป็น null

การป้องกันข้อผิดพลาดลำดับว่าง

int[] empty = { };
int min = empty.DefaultIfEmpty(int.MaxValue).Min(); // คืน int.MaxValue
// หรือ
int min = empty.Any() ? empty.Min() : 0; // คืน 0 หากว่าง