Dictionary<K,V> क्या है
एक Dictionary किसी key से values ढूंढता है, जैसे किसी dictionary में कोई शब्द या किसी phone book में कोई नाम ढूंढना। हर key तेज़ी से अपनी value की ओर इशारा करती है।
In this page:
Syntax
Dictionary<KeyType, ValueType> dictName = new Dictionary<KeyType, ValueType>();
dictName[key] = value;
ValueType value = dictName[key];
dictName.ContainsKey(key);
Dictionary<K,V>
Dictionary<TKey, TValue> key-value pairs store करता है और key से लगभग-constant-time lookup देता है। Keys unique होनी चाहिए; एक duplicate key जोड़ना एक exception फेंकता है जब तक आप इसे overwrite करने के लिए indexer उपयोग न करें।
जब भी आपको position के बजाय किसी meaningful identifier से values ढूंढनी हों यह go-to collection है।
Warning:
dict[key] से किसी गायब key को access करना एक KeyNotFoundException फेंकता है — सुरक्षित रूप से जांचने के लिए TryGetValue उपयोग करें।उदाहरण: Dictionary<K,V>
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 },
};
ages["Cara"] = 40;
if (ages.TryGetValue("Bob", out int bobAge))
{
Console.WriteLine(bobAge);
}
foreach (KeyValuePair<string, int> pair in ages)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
dict[key]से किसी गायब key को पढ़ना, जोKeyNotFoundExceptionफेंकता है;TryGetValueका उपयोग करें।Addसे पहले से मौजूद key जोड़ना, जोArgumentExceptionफेंकता है।- किसी mutable object को key के रूप में उपयोग करना और जोड़ने के बाद इसे बदलना, जिससे इसे अब ढूंढा नहीं जा सकता।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: