เมธอด Where() ใช้กรองลำดับ (Sequence) ตามเงื่อนไข (Predicate) ที่ระบุ คืนค่า IEnumerable<T> ที่มีเฉพาะองค์ประกอบที่ผ่านเงื่อนไข
รูปแบบพื้นฐาน
IEnumerableresult = source.Where(item => condition);
ตัวอย่าง: กรองค่ามากกว่าหรือเท่ากับ 70
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
int[] arr = { 10, 30, 20, 15, 90, 85, 40, 75 };
Console.WriteLine("อาร์เรย์เดิม:");
foreach (int a in arr) Console.WriteLine(a);
// กรองค่า >= 70
IEnumerable myQuery = arr.AsQueryable().Where((n, index) => n >= 70);
Console.WriteLine("ค่าที่ >= 70:");
foreach (int res in myQuery) Console.WriteLine(res);
}
}
ผลลัพธ์
อาร์เรย์เดิม: 10 30 20 15 90 85 40 75 ค่าที่ >= 70: 90 85 75
หมายเหตุ: พารามิเตอร์ index ใน Lambda เป็นดัชนีขององค์ประกอบ (เริ่มจาก 0) สามารถใช้ได้หากต้องการกรองตามตำแหน่ง