ภาพรวม
เมธอด GroupBy() ใน LINQ จัดกลุ่มองค์ประกอบในลำดับตาม คีย์ (key selector) คืนค่า IEnumerable<IGrouping<TKey, TElement>>
ตัวอย่าง: จัดกลุ่มตัวเลขน้อยกว่าหรือเท่า 50
using System;
using System.Linq;
class Demo
{
static void Main()
{
int[] arr = { 2, 30, 45, 60, 70 };
var groups = arr.GroupBy(x => x <= 50); // key = true/false
foreach (var group in groups)
{
Console.WriteLine(group.Key); // True / False
foreach (var item in group) Console.WriteLine(item);
}
}
// Helper method (optional)
static bool ChkSmaller(int a) => a <= 50;
}
ผลลัพธ์
True 2 30 45 False 60 70
รูปแบบการใช้งานทั่วไป
// 1. Group by property
var byDept = employees.GroupBy(e => e.Department);
// 2. Group by computed key
var byLength = words.GroupBy(w => w.Length);
// 3. Group with result selector
var summary = orders.GroupBy(o => o.CustomerId,
(key, group) => new { Customer = key, Total = group.Sum(o => o.Amount) });
// 4. Group into specific type
var lookup = items.ToLookup(x => x.Category); // ILookup - immediate execution
ข้อสังเกต
- Deferred execution - ไม่ทำงานจนกว่าจะ enumerate
- ลำดับกลุ่ม (groups) ตามลำดับที่ key ปรากฏครั้งแรกใน source
- ในแต่ละกลุ่ม ลำดับสมาชิกเหมือนใน source