[C#] Dictionary 사용법, 다양한 예제
더 보기: [C#] Dictionary 사용법, 다양한 예제
Key와 Value의 쌍으로 이루어진 Dictionary는 상당히 유용하다.
Value에는 형태를 구애 받지 않고 담을 수 있기에
활용도가 높다 하겠다.
■ 네임스페이스
using System; using System.Collections.Generic;
■ 선언 및 입력
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(100, "Jhon");
dict.Add(200, "Steven");
//또는
Dictionary<string, int> dic = new Dictionary<string, int>()
{
{"dog", 2},
{"iguana", -1},
{"cat", 1},
{"cow", 0}
};
//C# 6.0에서는
Dictionary<string, int> dic = new Dictionary<string, int>()
{
["dog"] = 2,
["cat"] = 1
}
<int, string> 말고 key,value쌍이라면 어떤 자료형을 선언해도 무방하다.
■ 사용예제
1. foreach
foreach (KeyValuePair<string, int> pair in dic)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
2. List
List<string> list = new List<string>(dic.Keys); foreach (string k in list) { Console.WriteLine("{0}, {1}", k, dic[k]); }
List<string> list = new List<string>(dic.Keys);
foreach (string k in list)
{
Console.WriteLine("{0}, {1}",
k,
dic[k]);
}
그냥 루프를 돌리는것 보다는
Key를 List에 할당한 후 루프를 돌리는 것이 훨씬 빠르다.
Dictionary는 위 예제와 같이 dic[키값] 형태로 Value를 얻을 수 있다.
3. 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);
}
4. LINQ를 이용해서 Array(배열)를 Dictionary로 변환하기(ToDictionary 사용법)
string[] arr = new string[]
{
"Hello",
"World"
};
var dict = arr.ToDictionary(item => item, item => true);
5. Index로 접근하기
Dictionary<int, int> dictionary = new Dictionary<int, int>(); dictionary[1] = 2; dictionary[2] = 1; dictionary[3] = 3; Console.WriteLine(dictionary[1]); Console.WriteLine(dictionary[2]);
Array와 같이 Index형태로 사용할 수도 있다.
6. 삭제
dic.Remove(key);
7. 다른 Dictionary 변수에 할당
Dictionary<string, string> newDictionary = oldDictionary.ToDictionary(k => k.Key, k => (string) k.Value);
//또는
Dictionary<string, string> newDictionary = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> item in oldDictionary)
{
newDictionary.Add(item.Key, item.Value.ToString());
//here item.Value.ToString() is an example
//you should convert your item to string according to the requirement
}
■ 활용 예제
1.dynamic
dynamic person = new ExpandoObject();
person.Name = "Kim";
person.Age = 10;
person.Display = (Action)(() => { });
person.ChangeAge = (Action<int>)((age) => { person.Age = age; });
person.AgeChanged = null;
person.AgeChanged += new EventHandler((s, e) => { });
// ExpandoObject를 IDictionary로 변환
var dict = (IDictionary<string, object>)person;
// person 의 속성,메서드,이벤트는
// IDictionary 해시테이블에 저정되어 있는데
// 아래는 이를 출력함
foreach (var d in dict)
{
Console.WriteLine("{0}: {1}", d.Key, d.Value);
}
2. LINQ를 이용한 ToList 활용
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("1", "test1");
d.Add("2", "test2");
dataGridView1.DataSource = (from entry in d
orderby entry.Key
select new{entry.Key,entry.Value}).ToList();
