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

Collection Initializers का उपयोग

Collection initializers आपको एक list बनाने और एक ही बार में भरने देते हैं, जैसे किसी lunchbox को इसके मिलते ही सभी items के साथ पैक करना। यह बहुत सारा दोहराया हुआ add करना बचाता है।

In this page:

  1. Collection Initializers
Syntax
csharp
List<type> list = new List<type> { value1, value2 };
Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>
{
    { key1, value1 },
    { key2, value2 },
};

Collection Initializers

Collection initializer syntax आपको किसी array, list, या dictionary को बनते ही { ... } से तुरंत भरने देता है, .Add() calls की एक अलग series के बिना।

यह किसी भी ऐसी type के लिए काम करता है जो IEnumerable implement करती है और जिसमें एक Add method हो। यह setup code को कहीं ज़्यादा compact और readable बनाता है।

Note: Object और collection initializers अच्छी तरह combine होते हैं — आप custom objects की एक list को एक expression में initialize कर सकते हैं।

उदाहरण: Collection Initializers

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3 };
        Dictionary<string, int> scores = new Dictionary<string, int>
        {
            { "Al", 10 },
            { "Bo", 20 },
        };

        Console.WriteLine(numbers.Count);
        Console.WriteLine(scores["Bo"]);
    }
}
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. new List<int> के बिना List<int> numbers = { 1, 2, 3 }; लिखना, जो एक compile error है क्योंकि अकेले braces सिर्फ arrays के लिए काम करते हैं।
  2. किसी Dictionary collection initializer में एक ही key को दो बार रखना, जैसे { { "a", 1 }, { "a", 2 } }, जो Add को दो बार call करता है और एक ArgumentException फेंकता है।
  3. यह सोचना कि एक initializer collection को fixed या read-only बना देता है, जबकि यह सिर्फ आपके लिए Add call करता है और collection बाद में अब भी बदली जा सकती है।
चैप्टर सारांश
  • Arrays, List<T>, Dictionary<K,V>, और HashSet<T> values के समूहों को अलग-अलग तरीकों से store करते हैं।
  • Queue और Stack first in first out और last in first out order handle करते हैं।
  • LINQ basics और collection initializers collections को संक्षेप में query और create करते हैं।
🔒

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.