logo
CSharp_Prog_Guide

Компиляция кода38

Для выполнения этого кода скопируйте класс в проект консольного приложения на языке Visual C#, которое было создано в среде разработки Visual Studio. По умолчанию этот проект предназначен для версии 3.5 платформы .NET Framework и имеет ссылку на библиотеку System.Core.dll и директиву using для пространства имен System.Linq. Если одно или более требований в проекте отсутствуют, их можно добавить вручную.

How to: Initialize a Dictionary with a Collection Initializer

A Dictionary<(Of <<TKey, TValue>>)>) contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value. To initialize a Dictionary<(Of <<TKey, TValue>)>>, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.

Example

In the following code example, a Dictionary<(Of <<TKey, TValue>)>> is initialized with instances of type Student.

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()

{

{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},

{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},

{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}

};

Note the three pairs of braces in each object initializer. The innermost braces enclose the object initializer for the Scores list. The next set encloses the initializer for the Student, and the outermost braces enclose the initializer for the key/value pair that will be added to the studentsDictionary<(Of <<TKey, TValue>)>>. Finally, the whole collection initializer is enclosed in braces.

Compiling the Code

To run this code, copy and paste the class into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 of the .NET Framework, and it has a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually.