C# में Dictionary<TKey, TValue>.ContainsKey() मेथड का उपयोग यह जांचने के लिए किया जाता है कि क्या निर्दिष्ट कुंजी डिक्शनरी में मौजूद है। यह true या false लौटाता है और अपवाद नहीं फेंकता।
उदाहरण
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
// डिक्शनरी बनाएं और तत्व जोड़ें
var dict = new Dictionary()
{
{ "TV", 1 },
{ "Home Theatre", 2 },
{ "Amazon Alexa", 3 },
{ "Google Home", 5 },
{ "Laptop", 5 },
{ "Bluetooth Speaker", 6 }
};
// ContainsKey() से कुंजी की जांच करें
string[] keysToCheck = { "Laptop", "Amazon Alexa", "iPhone", "TV" };
foreach (string key in keysToCheck)
{
if (dict.ContainsKey(key))
{
Console.WriteLine($"कुंजी: \"{key}\" - मिली! मान: {dict[key]}");
}
else
{
Console.WriteLine($"कुंजी: \"{key}\" - नहीं मिली");
}
}
}
}
आउटपुट
कुंजी: "Laptop" - मिली! मान: 5 कुंजी: "Amazon Alexa" - मिली! मान: 3 कुंजी: "iPhone" - नहीं मिली कुंजी: "TV" - मिली! मान: 1
ContainsKey() बनाम अन्य दृष्टिकोण
1. ContainsKey() + इंडेक्सर (दो लुकअप)
if (dict.ContainsKey(key))
{
var value = dict[key]; // दूसरा लुकअप
}
2. TryGetValue() - अनुशंसित (एक लुकअप)
if (dict.TryGetValue(key, out var value))
{
// value यहां उपलब्ध है
}
3. GetValueOrDefault() - C# 7.0+ (सबसे संक्षिप्त)
var value = dict.GetValueOrDefault(key, defaultValue);
प्रदर्शन तुलना
using System;
using System.Collections.Generic;
using System.Diagnostics;
public class Demo
{
public static void Main()
{
var dict = new Dictionary();
for (int i = 0; i < 100000; i++)
dict[i] = $"Value{i}";
int key = 50000;
int iterations = 1000000;
// ContainsKey + Indexer
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
if (dict.ContainsKey(key))
_ = dict[key];
}
Console.WriteLine($"ContainsKey + Indexer: {sw.ElapsedMilliseconds} ms");
// TryGetValue
sw.Restart();
for (int i = 0; i < iterations; i++)
{
dict.TryGetValue(key, out _);
}
Console.WriteLine($"TryGetValue: {sw.ElapsedMilliseconds} ms");
// GetValueOrDefault
sw.Restart();
for (int i = 0; i < iterations; i++)
{
_ = dict.GetValueOrDefault(key);
}
Console.WriteLine($"GetValueOrDefault: {sw.ElapsedMilliseconds} ms");
}
}
आउटपुट (सामान्य)
ContainsKey + Indexer: 45 ms TryGetValue: 28 ms GetValueOrDefault: 27 ms
महत्वपूर्ण बिंदु
ContainsKey()O(1) औसत समय जटिलता के साथ काम करता है- प्रदर्शन के लिए
TryGetValue()याGetValueOrDefault()पसंद करें ContainsKey()तब उपयोगी है जब आपको केवल उपस्थिति जाननी हो, मान नहीं- केस-सेंसिटिविटी डिक्शनरी के तुलनाकर्ता (comparer) पर निर्भर करती है
- null कुंजी की अनुमति है यदि डिक्शनरी इसे अनुमति देती है (
new Dictionaryडिफॉल्ट रूप से null की अनुमति नहीं देता)()