Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีตรวจสอบว่า Item มีอยู่ใน List C# หรือไม่

กำหนด List:

List<string> list1 = new List<string>() {
    "Lawrence", "Adams", "Pitt", "Tom"
};

ใช้ Contains() ตรวจสอบ:

if (list1.Contains("Adams") == true) {
    Console.WriteLine("Item exists!");
}

ตัวอย่าง

using System;
using System.Collections.Generic;
public class Program {
    public static void Main() {
        List<string> list1 = new List<string>() {
            "Lawrence", "Adams", "Pitt", "Tom"
        };
        Console.Write("List...\n");
        foreach(string list in list1) { Console.WriteLine(list); }
        Console.Write("Finding an item in the list...\n");
        if (list1.Contains("Adams") == true) {
            Console.WriteLine("Item exists!");
        } else {
            Console.WriteLine("Item does not exist!");
        }
    }
}