GroupBy() เป็นวิธีการขยายที่ส่งคืนกลุ่มขององค์ประกอบจากคอลเล็กชันที่กำหนดตามค่าคีย์บางค่า
ต่อไปนี้เป็นอาร์เรย์ของเรา -
int[] arr = { 2, 30, 45, 60, 70 }; ตอนนี้ เราจะใช้ GroupBy() เพื่อจัดกลุ่มองค์ประกอบที่เล็กกว่า 50 −
arr.GroupBy(b => chkSmaller(b));
chkSmaller() ด้านบนจะค้นหาองค์ประกอบที่เล็กกว่า 50
ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Linq;
class Demo {
static void Main() {
int[] arr = { 2, 30, 45, 60, 70 };
var check = arr.GroupBy(b => chkSmaller(b));
foreach (var val in check) {
Console.WriteLine(val.Key);
foreach (var res in val) {
Console.WriteLine(res);
}
}
}
static bool chkSmaller(int a) {
return a <= 50;
}
} ผลลัพธ์
True 2 30 45 False 60 70