logo

אתחול מילון C#

מאתחל C# Dictionary הוא תכונה המשמשת לאתחול רכיבי מילון. מילון הוא אוסף של אלמנטים. הוא מאחסן אלמנטים בצמד מפתח וערך.

אתחול המילון משתמש בסוגריים מסולסלים ({}) כדי להקיף את צמד המפתח והערכים.

בוא נראה דוגמה, שבה אנו מאתחלים ערך עבור כל מפתח.

C# Dictionary Initializer דוגמה 1

 using System; using System.Collections.Generic; namespace CSharpFeatures { class DictionaryInitializer { public static void Main(string[] args) { Dictionary dictionary = new Dictionary() { [1] = 'Irfan', [2] = 'Ravi', [3] = 'Peter' }; foreach (KeyValuePair kv in dictionary) { Console.WriteLine('{ Key = ' + kv.Key + ' Value = ' +kv.Value+' }'); } } } } 

תְפוּקָה:

 { Key = 1 Value = Irfan } { Key = 2 Value = Ravi } { Key = 3 Value = Peter } 

בדוגמה זו, אנו מאחסנים נתוני תלמידים במילון. אנו משתמשים באתחול מילון לאחסון נתוני תלמידים. ראה, את הדוגמה הבאה.

C# Dictionary Initializer דוגמה 2

 using System; using System.Collections.Generic; namespace CSharpFeatures { class Student { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } } class DictionaryInitializer { public static void Main(string[] args) { Dictionary dictionary = new Dictionary() { { 1, new Student(){ ID = 101, Name = 'Rahul Kumar', Email = '[email protected]'} }, { 2, new Student(){ ID = 102, Name = 'Peter', Email = '[email protected]'} }, { 3, new Student(){ ID = 103, Name = 'Irfan', Email = '[email protected]'} } }; foreach (KeyValuePair kv in dictionary) { Console.WriteLine('Key = '+kv.Key + ' Value = {' + kv.Value.ID +', '+ kv.Value.Name +', '+kv.Value.Email+'}'); } } } } 

תְפוּקָה:

 Key = 1 Value = {101, Rahul Kumar, [email protected] } Key = 2 Value = {102, Peter, [email protected] } Key = 3 Value = {103, Irfan, [email protected] }