C#에서 Dictionary는 일반적으로 키/값 쌍을 저장하는 데 사용되는 일반 컬렉션입니다. Dictionary의 작동은 제네릭이 아닌 hashtable과 매우 유사합니다. Dictionary의 장점은 Generic Type이라는 점입니다. 사전은 System.Collections.Generic 네임스페이스 아래에 정의됩니다. 본질적으로 동적이라는 것은 사전의 크기가 필요에 따라 커진다는 것을 의미합니다. 중요한 사항:
- Dictionary 클래스는 다음을 구현합니다.
- I사전 상호 작용
- IReadOnlyCollection
상호 작용 - IReadOnly사전 상호 작용
- I사전 상호 작용
- 사전에서 키는 null일 수 없지만 값은 null일 수 있습니다.
- 사전에서 키는 고유해야 합니다. 중복 키를 사용하려고 하면 중복 키가 허용되지 않으며 컴파일러에서 예외가 발생합니다.
- 사전에는 동일한 유형의 요소만 저장할 수 있습니다.
- 사전의 용량은 사전이 보유할 수 있는 요소의 수입니다.
사전을 만드는 방법은 무엇입니까?
사전 클래스에는 7명의 생성자 이는 사전을 생성하는 데 사용됩니다. 여기서는 Dictionary() 생성자만 사용하며 생성자에 대해 자세히 알아보려면 다음을 참조하세요. C# | 사전 클래스 . 사전(): 이 생성자는 비어 있고 기본 초기 용량을 가지며 다음과 같이 키 유형에 대한 기본 동등 비교자를 사용하는 Dictionary 클래스의 인스턴스를 만드는 데 사용됩니다. 1 단계: 키워드를 사용하여 프로그램의 includeSystem.Collections.Generic 네임스페이스를 사용합니다. 통사론:
using System.Collections.Generic;>
2 단계: 아래와 같이 Dictionary 클래스를 사용하여 사전을 만듭니다.
Dictionary dictionary_name = new Dictionary();>
3단계: 사전에 요소를 추가하려면 Add() 메서드를 사용하여 사전에 키/값 쌍을 추가하세요. 또한 Add 메서드를 사용하지 않고 사전에 키/값 쌍을 추가할 수도 있습니다. 아래 예와 같습니다. 4단계: 사전의 키/값 쌍은 다음을 사용하여 액세스됩니다. 삼 다른 방법들:
- for 루프: for 루프를 사용하여 사전의 키/값 쌍에 액세스할 수 있습니다. 예:
CSharp
SDLC
for>(>int> x=0; x { Console.WriteLine('{0} and {1}', My_dict1.Keys.ElementAt(x), My_dict1[ My_dict1.Keys.ElementAt(x)]); }> |
>
>
- 인덱스 사용: 인덱스 값을 사용하여 사전의 개별 키/값 쌍에 액세스할 수 있습니다. 여기서는 인덱스에 키를 지정하여 주어진 사전에서 값을 가져오며 인덱스를 지정할 필요가 없습니다. 인덱서는 항상 키를 매개변수로 사용하며, 주어진 키를 사전에서 사용할 수 없는 경우 다음을 제공합니다. KeyNotFound예외 . 예:
CSharp
Console.WriteLine('Value>is>:{0}', My_dicti[1123]);> Console.WriteLine('Value>is>:{0}', My_dicti[1125]);> |
>
>
- foreach 루프: foreach 루프를 사용하여 사전의 키/값 쌍에 액세스할 수 있습니다. 아래 예에서 볼 수 있듯이 foreach 루프를 사용하여 사전에 액세스합니다.
예:
CSharp
// C# program to illustrate how> // to create a dictionary> using> System;> using> System.Collections.Generic;> class> GFG {> >// Main Method> >static> public> void> Main () {> > >// Creating a dictionary> >// using Dictionary class> >Dictionary<>int>,>string>>My_dict1 => >new> Dictionary<>int>,>string>>();> > >// Adding key/value pairs> >// in the Dictionary> >// Using Add() method> >My_dict1.Add(1123, 'Welcome');> >My_dict1.Add(1124, 'to');> >My_dict1.Add(1125, 'techcodeview.com');> > >foreach>(KeyValuePair<>int>,>string>>엘레1>in> My_dict1)> >{> >Console.WriteLine('{0} and {1}',> >ele1.Key, ele1.Value);> >}> >Console.WriteLine();> > >// Creating another dictionary> >// using Dictionary class> >// adding key/value pairs without> >// using Add method> >Dictionary<>string>,>string>>My_dict2 => >new> Dictionary<>string>,>string>>(){> >{'a.1', 'Dog'},> >{'a.2', 'Cat'},> >{'a.3', 'Pig'} };> > >foreach>(KeyValuePair<>string>,>string>>ele2>>in> My_dict2)> >{> >Console.WriteLine('{0} and {1}', ele2.Key, ele2.Value);> >}> >}> }> |
>
>산출:
1123 and Welcome 1124 and to 1125 and techcodeview.com a.1 and Dog a.2 and Cat a.3 and Pig>
사전에서 요소를 제거하는 방법은 무엇입니까?
사전에서는 사전의 요소를 제거할 수 있습니다. Dictionary 클래스는 요소를 제거하는 두 가지 방법을 제공하며 해당 방법은 다음과 같습니다.
- 분명한 : 이 메서드는 사전에서 모든 키와 값을 제거합니다.
- 제거하다 : 이 메서드는 사전에서 지정된 키가 있는 값을 제거합니다.
예:
CSharp
// C# program to illustrate how> // remove key/value pairs from> // the dictionary> using> System;> using> System.Collections.Generic;> class> GFG {> >// Main Method> >static> public> void> Main() {> > >// Creating a dictionary> >// using Dictionary class> >Dictionary<>int>,>string>>내_dict => >new> Dictionary<>int>,>string>>();> > >// Adding key/value pairs in the> >// Dictionary Using Add() method> >My_dict.Add(1123, 'Welcome');> >My_dict.Add(1124, 'to');> >My_dict.Add(1125, 'techcodeview.com');> > >// Before Remove() method> >foreach>(KeyValuePair<>int>,>string>>그>in> My_dict)> >{> >Console.WriteLine('{0} and {1}',> >ele.Key, ele.Value);> >}> >Console.WriteLine();> > >// Using Remove() method> >My_dict.Remove(1123);> > >// After Remove() method> >foreach>(KeyValuePair<>int>,>string>>그>in> My_dict)> >{> >Console.WriteLine('{0} and {1}',> >ele.Key, ele.Value);> >}> >Console.WriteLine();> > > >// Using Clear() method> >My_dict.Clear();> > >Console.WriteLine('Total number of key/value '+> >'pairs present>in> My_dict:{0}', My_dict.Count);> > >}> }> |
>
>산출:
쿠미트 같은 사이트
1123 and Welcome 1124 and to 1125 and techcodeview.com 1124 and to 1125 and techcodeview.com Total number of key/value pairs present in My_dict:0>
사전에서 요소의 가용성을 확인하는 방법은 무엇입니까?
Dictionary에서는 주어진 키나 값이 지정된 Dictionary에 존재하는지 여부를 확인할 수 있습니다. Dictionary 클래스는 확인을 위한 두 가지 방법을 제공하며 방법은 다음과 같습니다.
- 키 포함 : 이 메소드는 사전에 지정된 키가 포함되어 있는지 확인하는 데 사용됩니다.
- 포함값 : 이 메소드는 Dictionary에 특정 값이 포함되어 있는지 확인하는 데 사용됩니다.
예:
CSharp
// C# program to illustrate how> // to check the given key or> // value present in the dictionary> // or not> using> System;> using> System.Collections.Generic;> class> GFG {> >// Main Method> >static> public> void> Main () {> > >// Creating a dictionary> >// using Dictionary class> >Dictionary<>int>,>string>>내_dict => >new> Dictionary<>int>,>string>>();> > >// Adding key/value pairs in the> >// Dictionary Using Add() method> >My_dict.Add(1123, 'Welcome');> >My_dict.Add(1124, 'to');> >My_dict.Add(1125, 'techcodeview.com');> > >// Using ContainsKey() method to check> >// the specified key is present or not> >if> (My_dict.ContainsKey(1122)==>true>)> >{> >Console.WriteLine('Key>is> found...!!');> >}> >else> >{> >Console.WriteLine('Key>is> not found...!!');> >}> > >// Using ContainsValue() method to check> >// the specified value is present or not> >if> (My_dict.ContainsValue('techcodeview.com')==>true>)> >{> >Console.WriteLine('Value>is> found...!!');> >}> >else> >{> >Console.WriteLine('Value>is> not found...!!');> >}> >}> }> |
>
>산출:
Key is not found...!! Value is found...!!>