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

C# Dictionary 복사 예제, 딕셔너리 class copy 사용법

by vicddory 2017. 4. 6.

C# 딕셔너리 복사 방법


Dictionary 복사. C# Dictionary에는 복사 생성자가 있습니다. 기존 딕셔너리 객체를 생성자로 넘기면 그대로 복사가 되는데, 현재로썬 가장 효율적인 방법입니다. 그리고 기존 딕셔너리를 수정해도 복사된 데이터엔 영향을 주지 않습니다.


예제. 간단한 반복문을 구현하여 C# Dictionary 아이템을 직접 복사할 경우엔 코드 중복 및 예상치 못한 에러가 발생할 수 있습니다. 반복문 자체가 비효율적이란 것이죠.


Here: 아래 예제에선 복사 생성자를 사용해 딕셔너리 내부 데이터를 복사합니다.


using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
//
// Create and initialize Dictionary.
//
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 1);
dictionary.Add("dog", 3);
dictionary.Add("iguana", 5);
//
// Copy the C# Dictionary to a second object.
//
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
//
// Change the first Dictionary. It won't change the copy.
//
dictionary.Add("fish", 4);
//
// Display the first Dictionary.
//
Console.WriteLine("--- Dictionary 1 ---");
foreach (var pair in dictionary)
{
Console.WriteLine(pair);
}
//
// Display the second Dictionary.
//
Console.WriteLine("--- Dictionary 2 ---");
foreach (var pair in copy)
{
Console.WriteLine(pair);
}
}
}



Output
(Modifying the first C# Dictionary doesn't affect the copied Dictionary.)
--- Dictionary 1 ---
[cat, 1]
[dog, 3]
[iguana, 5]
[fish, 4]
--- Dictionary 2 ---
[cat, 1]
[dog, 3]
[iguana, 5]


위 c# 코드는 새로운 딕셔너리 초기화를 먼저하고 메인 진입점을 정의합니다. 그리고 세 개의 key-value를 새 딕셔너리에 복사합니다.

Finally: 복사가 끝난 뒤, 기존 딕셔너리에 키를 추가하고 콘솔로 데이터 전체를 확인합니다. 새 딕셔너리에는 복사 이후 추가된 데이터가 보이지 않습니다. (이미 복사된 딕셔너리엔 기존 딕셔너리 수정 사항이 반영되지 않음)


Internals. 직접 데이터를 복사하는 방법도 있습니다. IDictionary를 상속받는 루프를 이용할 수 있죠.


foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
this.Add(pair.Key, pair.Value);
}


Summary. 위에서 딕셔너리 복사 방법을 다뤘습니다. C# Dictionary 클래스는 Copy(), CopyTo() 함수를 제공하지 않기에 복사 생성자를 사용하기가 가장 쉽고 명확합니다.


C# 딕셔너리 예제 더보기

기초 9가지 사용 방법

C# Dictionary 9가지 사용법, 딕셔너리 예제
Dictionary에 키값 4개를 추가한 뒤 비주얼 스튜디오 디버거를 통해 내용을 확인합니다. Dictionary는 키와 값을 쌍으로 보유합니다. string, int 다른 자료형을 요소로 사용합니다. using System; using System.C..
codingcoding.tistory.com


TryGetValue, out 예제

C# Dictionary Value 값 가져오기 (TryGetValue, out 예제)
C# Dictionary Value 값 가져오기 (TryGetValue, out 예제) C# 딕셔너리에서 값을 가져오려면 당연히 키 값을 인자로 전달해야 합니다. 그리고 변수를 따로 선언해 Dictionary 값을 할당하는데요. 하지만, out 키..
codingcoding.tistory.com


ContainsValue, Indexer, Clear 예제 3개

C# Dictionary ContainsValue, 인덱서, Clear 예제 3개
C# Dictionary, ContainsValue, 인덱서, Clear 예제 3개 ContainsValue. 이 함수는 ContainsKey 보다 아주 느립니다. 전체를 순회하는 복잡한 선형 구조입니다. 모든 요소를 탐색하며 일치하는 항목을 찾거나, 순..
codingcoding.tistory.com


댓글