Dictionary<TKey, TValue>.ContainsKey(TKey key) মেথড ব্যবহার করে ডিকশনারিতে নির্দিষ্ট কী আছে কিনা O(1) গড় সময়ে যাচাই করা যায়। এটি বুলিয়ান রিটার্ন করে। ডিকশনারি হ্যাশ টেবিল বেসড, তাই কী লুকআপ খুব দ্রুত। কী null হতে পারে না (রেফারেন্স টাইপের জন্য)।
উদাহরণ ১: বিদ্যমান কী খোঁজা (সাফল্য)
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("এলিমেন্ট সংখ্যা = " + dict.Count);
Console.WriteLine("\nকী/মান জোড়া...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("Three")) {
Console.WriteLine("কী পাওয়া গেল!");
} else {
Console.WriteLine("কী ডিকশনারিতে নেই!");
}
dict.Clear();
Console.WriteLine("ক্লিয়ার করা কী/মান জোড়া...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("এলিমেন্ট সংখ্যা এখন = " + dict.Count);
}
}
আউটপুট
এলিমেন্ট সংখ্যা = 5 কী/মান জোড়া... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan কী পাওয়া গেল! ক্লিয়ার করা কী/মান জোড়া... এলিমেন্ট সংখ্যা এখন = 0
উদাহরণ ২: অস্তিত্বহীন কী খোঁজা (ব্যর্থতা)
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("এলিমেন্ট সংখ্যা = " + dict.Count);
Console.WriteLine("\nকী/মান জোড়া...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
if (dict.ContainsKey("mykey")) {
Console.WriteLine("কী পাওয়া গেল!");
} else {
Console.WriteLine("কী ডিকশনারিতে নেই!");
}
dict.Clear();
Console.WriteLine("ক্লিয়ার করা কী/মান জোড়া...");
foreach(KeyValuePair<string, string> res in dict) {
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("এলিমেন্ট সংখ্যা এখন = " + dict.Count);
}
}
আউটপুট
এলিমেন্ট সংখ্যা = 5 কী/মান জোড়া... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan কী ডিকশনারিতে নেই! ক্লিয়ার করা কী/মান জোড়া... এলিমেন্ট সংখ্যা এখন = 0
দ্রষ্টব্য: ContainsKey() হ্যাশ-ভিত্তিক লুকআপ করে (O(1))। ContainsValue() O(n) লিনিয়ার সার্চ করে। TryGetValue() ব্যবহার করে একই সময়ে কী চেক এবং মান পাওয়ার সুযোগ থাকে (আরো দক্ষ)।