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

เมธอด Aggregate() ใน C#

เมธอด Aggregate() ใช้ทำการสะสม (Accumulate) ค่าผ่านลำดับ โดยใช้ฟังก์ชันสะสม (Accumulator Function) ที่รับค่าสะสมก่อนหน้าและองค์ประกอบปัจจุบัน แล้วคืนค่าสะสมใหม่

ตัวอย่าง: หาสตริงที่ยาวที่สุด (เปรียบเทียบกับค่าเริ่มต้น "DemoFive")

using System;
using System.Linq;

class Demo
{
    static void Main()
    {
        string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour" };
        
        // seed = "DemoFive", func = เลือกสตริงที่ยาวกว่า, resultSelector = แปลงเป็นตัวพิมพ์เล็ก
        string res = arr.AsQueryable().Aggregate(
            "DemoFive",
            (longest, next) => next.Length > longest.Length ? next : longest,
            str => str.ToLower()
        );
        
        Console.WriteLine("สตริงที่มีตัวอักษรมากที่สุด: {0}", res);
    }
}

ผลลัพธ์

สตริงที่มีตัวอักษรมากที่สุด: demothree

พารามิเตอร์ 3 ตัว: 1) Seed (ค่าเริ่มต้น), 2) Func (ฟังก์ชันสะสม), 3) Result Selector (แปลงผลลัพธ์สุดท้าย - Optional)