ใช้เมธอด Where() ของ LINQ ร่วมกับ Lambda Expression เพื่อกรององค์ประกอบในอาร์เรย์ตามเงื่อนไขที่กำหนด
ตัวอย่าง: กรองค่าที่มากกว่าหรือเท่ากับ 50
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
int[] arr = { 40, 42, 12, 83, 75, 40, 95 };
Console.WriteLine("อาร์เรย์เดิม:");
foreach (int a in arr) Console.WriteLine(a);
// กรองค่า >= 50
IEnumerable myQuery = arr.AsQueryable().Where((a, index) => a >= 50);
Console.WriteLine("ค่าที่ >= 50:");
foreach (int res in myQuery) Console.WriteLine(res);
}
}
ผลลัพธ์
อาร์เรย์เดิม: 40 42 12 83 75 40 95 ค่าที่ >= 50: 83 75 95
พารามิเตอร์ index: Lambda สามารถรับพารามิเตอร์ที่สองเป็นดัชนี (index) ได้ หากต้องการกรองตามตำแหน่ง