ภาพรวม
เมธอด Contains() ใน LINQ ใช้ตรวจสอบว่าองค์ประกอบเฉพาะมีอยู่ในลำดับหรือไม่ คืนค่า bool (true หากพบ, false หากไม่พบ)
รูปแบบการใช้งาน
string[] arr = { "Java", "C++", "Python" };
string search = "Python";
bool hasPython = arr.AsQueryable().Contains(search); // true
ตัวอย่างโค้ดเต็ม
using System;
using System.Linq;
using System.Collections.Generic;
class Demo
{
static void Main()
{
string[] arr = { "Java", "C++", "Python" };
string str = "Python";
bool res = arr.AsQueryable().Contains(str);
Console.WriteLine("Array has Python? " + res);
}
}
ผลลัพธ์
Array has Python? True
ข้อสังเกต
- ใช้การเปรียบเทียบแบบค่าเริ่มต้น (default equality comparer)
- สำหรับสตริง ค่าเริ่มต้นคือ case-sensitive
- ต้องการ case-insensitive:
arr.Contains(str, StringComparer.OrdinalIgnoreCase)(ต้องใช้ overload ที่รับ comparer) - ประสิทธิภาพ O(n) สำหรับอาร์เรย์/ลิสต์; ใช้
HashSetสำหรับ O(1)