ประกอบด้วยคีย์คือเมธอดของพจนานุกรมในภาษา C# และตรวจสอบว่าคีย์มีอยู่ในพจนานุกรมหรือไม่
ประกาศพจนานุกรมและเพิ่มองค์ประกอบ -
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
}; ตอนนี้ สมมติว่าคุณต้องตรวจสอบการมีอยู่ขององค์ประกอบเฉพาะในพจนานุกรม สำหรับสิ่งนั้น ให้ใช้เมธอด ContainKey() −
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
} ต่อไปนี้เป็นรหัส −
ตัวอย่าง
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
};
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
}
if (dict.ContainsKey("Amazon Alexa") == true) {
Console.WriteLine(dict["Amazon Alexa"]);
}
}
} ผลลัพธ์
5 3