Ngôn ngữ LINQ - Toán tử Min

Toán tử Min trong LINQ

Trái ngược với toán tử Max, toán tử Min trả về phần tử kiểu số nhỏ nhất từ ​​danh sách.

Ví dụ sau đây minh họa cách sử dụng phương thức Min trên danh sách kiểu nguyên thủy.

IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };

var smallest = intList.Min();

Console.WriteLine("Smallest Element: {0}", smallest);

var smallestOddElements = intList.Min(i => i % 2 != 0 ? i : 0);

Console.WriteLine("Smallest Odd Element: {0}", smallestOddElements );

Đây là kết quả khi biên dịch và thực thi chương trình:

Smallest Element: 10
Smallest Odd Element: 21

Xem ví dụ

Ví dụ sau đây minh họa sử dụng phương thức Min trên danh sách kiểu phức tạp.

IList<Student> studentList = new List<Student>() 
{ 
    new Student() { StudentID = 1, StudentName = "John", Age = 13 },
    new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 },
    new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 },
    new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
    new Student() { StudentID = 5, StudentName = "Ron", Age = 15 } 
};

var youngest = studentList.Min(s => s.Age);

Console.WriteLine("Youngest Student Age: {0}", youngest);

Đây là kết quả khi biên dịch và thực thi chương trình:

Youngest Student Age: 13

Xem ví dụ

Phương thức Min trả về kết quả của bất kỳ kiểu dữ liệu nào. Ví dụ sau đây cho thấy cách bạn có thể tìm thấy một sinh viên có tên ngắn nhất trong danh sách:

public class Student : IComparable<Student> 
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
    public int StandardID { get; set; }

    public int CompareTo(Student other)
    {
        if (this.StudentName.Length > other.StudentName.Length)
        {
            return 1;
        }
        else if (this.StudentName.Length < other.StudentName.Length)
        {
            return -1;
        }
        return 0;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Student collection
        IList<Student> studentList = new List<Student>() 
        { 
            new Student() { StudentID = 1, StudentName = "John", Age = 13 },
            new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 },
            new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 },
            new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
            new Student() { StudentID = 5, StudentName = "Ronney", Age = 15 } 
        };

        var studentWithShortName = studentList.Min();

        Console.WriteLine("Student ID: {0}, Student Name: {1}", 
            studentWithShortName.StudentID, studentWithShortName.StudentName);
    }
}

Đây là kết quả khi biên dịch và thực thi chương trình:

Student ID: 1, Student Name: Johnny

Xem ví dụ

Lưu ý: Toán tử Min không hỗ trợ cú pháp truy vấn trong LINQ.