Section 48.16: 확장 메소드를 사용하여 새로운 collection 타입 (예:DictList) 생성하기

List<T> 를 값으로 갖는 Dictionary 와 같은, 새로운 중첩 collection 타입을 확장메소드를 통해 보다 편리하게 사용할 수 있도록 만들 수 있다.

다음과 같은 확장 메소드가 있다고 가정하면:

public static class DictListExtensions { public static void Add < TKey, TValue, TCollection > (this Dictionary < TKey, TCollection > dict, TKey key, TValue value) where TCollection: ICollection < TValue > , new() { TCollection list; if (!dict.TryGetValue(key, out list)) { list = new TCollection(); dict.Add(key, list); } list.Add(value); } public static bool Remove < TKey, TValue, TCollection > (this Dictionary < TKey, TCollection > dict, TKey key, TValue value) where TCollection: ICollection < TValue > { TCollection list; if (!dict.TryGetValue(key, out list)) { return false; } var ret = list.Remove(value); if (list.Count == 0) { dict.Remove(key); } return ret; } }

위 확장 메소드를 다음과 같이 사용할 수 있다:

var dictList = new Dictionary<string, List<int>>(); dictList.Add("example", 5); dictList.Add("example", 10); dictList.Add("example", 15); Console.WriteLine(String.Join(", ", dictList["example"])); // 5, 10, 15 dictList.Remove("example", 5); dictList.Remove("example", 10); Console.WriteLine(String.Join(", ", dictList["example"])); // 15 dictList.Remove("example", 15); Console.WriteLine(dictList.ContainsKey("example")); // False

데모 확인하기

본 문서는 C# Notes for Professionals (라이센스:CC-BY-SA) 를 한글로 번역한 문서입니다. 번역상 오류가 있을 수 있으므로 정확한 내용은 원본 문서를 참고하세요.

[출처] https://books.goalkicker.com/CSharpBook/

반응형

+ Recent posts