C#의 알아두면 편할 기능 (3/3)
작성 2019년 12월 22일 김태겸
7. Dictionary Collection
Dictionary는 C#에서 지원하는 콜렉션 중 하나로 Key와 Value의 쌍으로 이루어져 있으며, Value의 경우 형태를 구애받지 않고 담을 수 있어 활용도가 높습니다.
- 네임스페이스 선언
using System; using System.Collections.Generic;
- 선언 및 입력
// 선언방법 1 Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "TGKIM"); dict.Add(2, "tgkim"); // 선언방법 2 Dictionary<string, int> dict2 = new Dictionary<string, int>() { {"tgkim", 1}, {"TGKIM", 2} }; // C# 6.0 지원 기능 Dictionary<string, int> coffeeDic = new Dictionary<string, int>() { ["아메리카노"] = 1500, ["카페라떼"] = 2000 }
Key와 Value의 쌍이라면 어떤 자료형이든 넣을 수 있다.
- 사용 예제
- Foreach 문 사용
foreach (KeyValuePair<string, int> pair in dic) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); }
- Key 혹은 Value의 값 확인
//Dictionary에 해당 Key값이 있는지 확인 Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(100, "Jhon"); dict.Add(200, "Steven"); if (dict.ConstainKey(200)) { Console.WriteLine(true); } //Dictionary에 해당 Value값이 있는지 확인 Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("dog", 1); dict.Add("cow", 2); if (dict.ContainsValue(1)) { Console.WriteLine(true); }
- Index로 접근하기
Dictionary<int, int> dictionary = new Dictionary<int, int>(); dictionary[1] = 2; dictionary[2] = 1; dictionary[3] = 3; Console.WriteLine(dictionary[1]); // 2 출력 Console.WriteLine(dictionary[2]); // 1 출력
- Foreach 문 사용
8. Property 초기화 (Auto-Property) (C# 6.0 ~)
Auto-Property는 개발자가 필드를 지정할 필요가 없어 C# 컴파일러가 자동으로 해당 필드를 만들어주는 Property 이다. 예를 들어 개발자가 다음과 같이 선언을 할 경우
public string Name {get; set;}
Name 이라는 속성이 실제르 읽고 쓰는 필드를 컴파일러가 자동으로 생성한다.
이러한 자동 속성 기능은 기존에 지원하던 기능이나, C# 6.0에서 이 자동 속성에 초기값을 지원하는 기능이 추가되었다.
사용 방법은 다음과 같다.
class Markany
{
public string Pos { get; set; } = "중구 쌍림동";
}
C# 6.0 이전의 자동 속성은 get 과 set을 함께 사용하였다. 외부에 읽기만 허용할 경우
{get; private set; }
처럼 set 엑세스를 제한하였으나, set 생략은 불가능 하였다.
C# 6.0에서는 읽기 전용(readonly)의 자동 속성 사용이 가능해졌다. 읽기 전용 자동 속성에 값을 할당하지 않을 경우 자동으로 default 값을 할당되며, 초기값을 지정할 경우는 다음과 같이 사용한다.
class Person
{
public string Name { get; set; } = "(No name)";
// 초기화 없을 경우 디폴드값 사용됨
public string Nickname { get; }
public int Age { get; }
// Auto-Property Initializer 할당
public bool Enabled { get; } = true;
// 생성자에서 초기값 할당
public int Level { get; }
public Person()
{
this.Level = 1;
}
}
static void Main(string[] args)
{
Person p = new Person();
Console.WriteLine(p.Name);
Console.WriteLine(p.Nickname); // null 출력
Console.WriteLine(p.Age); // 0 출력
}