Collection Initializers का उपयोग
Collection initializers आपको एक list बनाने और एक ही बार में भरने देते हैं, जैसे किसी lunchbox को इसके मिलते ही सभी items के साथ पैक करना। यह बहुत सारा दोहराया हुआ add करना बचाता है।
In this page:
Syntax
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
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"]);
}
}
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. #}
आम गलतियां
new List<int>के बिनाList<int> numbers = { 1, 2, 3 };लिखना, जो एक compile error है क्योंकि अकेले braces सिर्फ arrays के लिए काम करते हैं।- किसी
Dictionarycollection initializer में एक ही key को दो बार रखना, जैसे{ { "a", 1 }, { "a", 2 } }, जोAddको दो बार call करता है और एकArgumentExceptionफेंकता है। - यह सोचना कि एक initializer collection को fixed या read-only बना देता है, जबकि यह सिर्फ आपके लिए
Addcall करता है और collection बाद में अब भी बदली जा सकती है।
चैप्टर सारांश
- Arrays,
List<T>,Dictionary<K,V>, औरHashSet<T>values के समूहों को अलग-अलग तरीकों से store करते हैं। QueueऔरStackfirst 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: