← Back to C# Course | Chapter 9: Collections | Lesson 3 of 7

Dictionary<K,V> क्या है

एक Dictionary किसी key से values ढूंढता है, जैसे किसी dictionary में कोई शब्द या किसी phone book में कोई नाम ढूंढना। हर key तेज़ी से अपनी value की ओर इशारा करती है।

In this page:

  1. Dictionary<K,V>
Syntax
csharp
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>

markup
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}");
        }
    }
}
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. #}
आम गलतियां
  1. dict[key] से किसी गायब key को पढ़ना, जो KeyNotFoundException फेंकता है; TryGetValue का उपयोग करें।
  2. Add से पहले से मौजूद key जोड़ना, जो ArgumentException फेंकता है।
  3. किसी mutable object को key के रूप में उपयोग करना और जोड़ने के बाद इसे बदलना, जिससे इसे अब ढूंढा नहीं जा सकता।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.