วิธี Aggregate() ใช้ฟังก์ชันตัวสะสมบนลำดับ
ต่อไปนี้เป็นอาร์เรย์ของเรา -
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"}; ตอนนี้ใช้เมธอด Aggregate() เราได้ตั้งค่า ssed เป็น “DemoFive” เพื่อเปรียบเทียบ
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower()); ในที่นี้ สตริงผลลัพธ์ควรมีจำนวนอักขระมากกว่าค่าเริ่มต้น เช่น “DemoFive”
ตัวอย่าง
using System;
using System.Linq;
class Demo {
static void Main() {
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());
Console.WriteLine("The string with more number of characters: {0}", res);
}
} ผลลัพธ์
The string with more number of characters: demothree