본문 바로가기
C++ 200제/코딩 IT 정보

C# Dictionary ContainsValue, 인덱서, Clear 예제 3개

by vicddory 2018. 10. 8.

C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개 


ContainsValue. 이 함수는 ContainsKey 보다 아주 느립니다. 전체를 순회하는 복잡한 선형 구조입니다. 모든 요소를 탐색하며 일치하는 항목을 찾거나, 순회가 끝나면 종료합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        Dictionary<stringint> d = new Dictionary<stringint>();
        d.Add("cat"1);
        d.Add("dog"2);
 
        if (d.ContainsValue(1))
        {
            Console.WriteLine(true); // True.
        }
    }
}
 
cs



Dictionary - key[C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개]




인덱서. Dictionary에 값을 추가할 때 항상 Add 함수를 쓰지 않아도 됩니다. ["key"] 괄호를 이용한 인덱서로 키를 할당할 수 있습니다.


  • 단, 이미 존재하는 키에 대해선 에러가 발생합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        Dictionary<intint> dictionary = new Dictionary<intint>();
 
        // We can assign with the indexer.
        dictionary[1= 2;
        dictionary[2= 1;
        dictionary[1= 3// Reassign.
 
        // Read with the indexer.
        // ... An exception occurs if no element exists.
        Console.WriteLine(dictionary[1]);
        Console.WriteLine(dictionary[2]);
    }
}
cs



C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개[C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개]



Clear. 이 함수로 모든 데이터를 지웁니다. Dictionary 변수가 null로 할당되며 가비지 컬렉터가 실행됩니다.




Count. Dictionary에 있는 키의 개수를 리턴합니다.



씨샵 로고[C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개]



Remove. String.Empty나 null로 값을 설정하거나 제거할 수 있지만, 키를 삭제할 순 없습니다. 아래는 『요소 삭제 예제』입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        Dictionary<stringint> d = new Dictionary<stringint>();
        d.Add("cat"1);
        d.Add("dog"2);
 
        d.Remove("cat"); // Removes cat.
        d.Remove("nothing"); // Doesn't remove anything.
    }
}
cs


Copy. Dictionary에는 모든 값을 복사하는 생성자를 제공합니다. 코드 재사용성이 높아지죠.


Return. Dictionary는 클래스 형태로 인수나 리턴값으로 사용할 수 있습니다.


 C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개

댓글