ตัวอย่างที่ 1: ผลรวมสะสม (Sum)
=List.Accumulate({1, 2, 3, 4, 5}, 0, (state, current) => state + current)
15
วนลูปคำนวณและสะสมค่าจากสมาชิกใน List
List.Accumulate จะรับ List และค่าเริ่มต้น (Seed) จากนั้นจะส่งค่าเข้าไปในฟังก์ชัน Accumulator ทีละรอบ เพื่อนำค่าปัจจุบัน (Current) ไปคำนวณร่วมกับค่าสะสม (State) และส่งต่อผลลัพธ์ไปรอบถัดไป
=List.Accumulate(list as list, seed as any, accumulator as function) as any
=List.Accumulate(list as list, seed as any, accumulator as function) as any
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| list | list | Yes | List ที่ต้องการนำมาวนลูป | |
| seed | any | Yes | ค่าเริ่มต้น (Initial Value) สำหรับเริ่มการสะสม | |
| accumulator | function | Yes | ฟังก์ชันที่กำหนดวิธีการคำนวณ (รับค่า state, current) |
วนลูปยอดรายรับ-รายจ่าย เพื่อหายอดเงินคงเหลือสุดท้าย
วนลูป List ของคำที่ต้องการเปลี่ยน เพื่อแทนที่คำเหล่านั้นในข้อความหลักทีละคำ (Bulk Replace)
รวมข้อความจาก List เข้าด้วยกันโดยใส่ตัวคั่นเฉพาะจุดที่ต้องการ
=List.Accumulate({1, 2, 3, 4, 5}, 0, (state, current) => state + current)
15
=List.Accumulate({{"Old", "New"}, {"Bad", "Good"}}, "This is Old and Bad", (state, current) => Text.Replace(state, current{0}, current{1}))
This is New and Good
=List.Accumulate({1, 2, 3}, {}, (state, current) => state & {current * 2})
{2, 4, 6}
List.Sum หาผลรวมตัวเลขได้อย่างเดียว แต่ List.Accumulate สามารถทำอะไรก็ได้ที่ต้องการวนลูป (เช่น รวมข้อความ, สร้าง List ใหม่)
ฟังก์ชัน List.Accumulate ใน Power Query ใช้สำหรับวนลูป (Loop) ผ่านสมาชิกแต่ละตัวใน List เพื่อทำการคำนวณและสะสมค่าไปเรื่อยๆ (Accumulate) จนได้ผลลัพธ์สุดท้าย คล้ายกับฟังก์ชัน REDUCE ใน Excel