logo

Inicialitzador de diccionaris C#

L'inicialitzador de diccionari C# és una característica que s'utilitza per inicialitzar elements del diccionari. El diccionari és una col·lecció d'elements. Emmagatzema elements en parella clau i valor.

L'inicialitzador de diccionari utilitza claus ({}) per incloure la parella clau i valor.

Vegem un exemple, en el qual estem inicialitzant el valor de cada clau.

Exemple 1 de l'inicialitzador del diccionari C#

 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+' }'); } } } } 

Sortida:

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

En aquest exemple, estem emmagatzemant les dades dels estudiants al diccionari. Estem utilitzant l'inicialitzador de diccionari per emmagatzemar les dades dels estudiants. Vegeu, l'exemple següent.

Exemple 2 de l'inicialitzador de diccionaris C#

 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+'}'); } } } } 

Sortida:

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