Sử dụng Aggregate() với lambda để tìm chuỗi có độ dài lớn nhất. Aggregate tích lũy kết quả qua từng phần tử.
Ví dụ minh họa
using System;
using System.Linq;
class Demo
{
static void Main()
{
string[] arr = { "Java", "HTML", "CSS", "JavaScript" };
string res = arr.AsQueryable()
.Aggregate("jQuery", (longest, next) => next.Length > longest.Length ? next : longest,
str => str.ToLower());
Console.WriteLine("Chuỗi có nhiều ký tự nhất: {0}", res);
}
}
Kết quả đầu ra
Chuỗi có nhiều ký tự nhất: javascript
Giải thích Aggregate 3 tham số:
seed: giá trị khởi tạo ("jQuery")func: hàm tích lũy (so sánh độ dài, giữ chuỗi dài hơn)resultSelector: biến đổi kết quả cuối (ToLower)
Cách đơn giản hơn: arr.OrderByDescending(s => s.Length).First() hoặc arr.MaxBy(s => s.Length) (.NET 6+).