프로그래밍 언어/C#

C# ILookup과 Lookup<TKey, TElement>와 Dictionary<TKey, TValue>간 차이

ShovelingLife 2022. 8. 7. 18:48

Dictionary <TKey, TValue> 는 키를 단일 값에 매핑하는 반면 Lookup <TKey, TElement> 는 키를 값 컬렉션에 매핑한다.

값 컬렉션이라고 하면은 LINQ에서 반환되는 모든 값들을 뜻한다고 볼 수가 있다.

 

아래는 Type 리플렉션을 사용한 예제이다.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Xml;

namespace ConsoleApplication1
{
    public class Test
    {
        static void Main()
        {
            // Type형 배열에 List<T> 타입, string 타입, Enumerable 타입 그리고 XmlReader 타입 추가
            Type[] arrSampleTypes = new[]
            { typeof(List<>),
              typeof(string),
              typeof(Enumerable),
              typeof(XmlReader)
            };
            // Assembly 추상 클래스에서 컴파일러의 모든 타입들을 가져옴
            IEnumerable<Type> allTypes = arrSampleTypes.Select(t => t.Assembly)
                                                       .SelectMany(a => a.GetTypes());

            // ILookup은 인터페이스 용 최상위 클래스
            ILookup<string, Type> IlookUp = allTypes.ToLookup(t => t.Namespace);

            // Lookup 사용 시 다운캐스팅 해야함 (ILookup > Lookup)
            Lookup<string, Type> lookUp = allTypes.ToLookup(t => t.Namespace) as Lookup<string, Type>;

            // Lookup 리플렉션에 의하여 System 키에 포함되있는걸 불러옴
            foreach (Type type in IlookUp["System"])
                     Console.WriteLine("{0}: {1}", type.FullName, type.Assembly.GetName().Name);


        }
    }
}

아래는 string 타입을 사용한 예제이다.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Xml;

namespace ConsoleApplication1
{
    public class Test
    {
        static void Main()
        {
            List<string> names = new List<string>(new string[] { "Smith", "Stevenson", "Jones" });

            //// 또는 아래를 사용할 수가 있음.
            //names.Add("Smith");
            //names.Add("Stevenson");
            //names.Add("Jones");

            // S S J 각 대문자들을 갖고 온다 string형 배열 0번째 원소
            ILookup<char, string> namesByInitial = names.ToLookup((n) => n[0]);

            // 가져온걸 개수를 센다
            Console.WriteLine("J's: {0}", namesByInitial['J'].Count()); // 1
            Console.WriteLine("S's: {0}", namesByInitial['S'].Count()); // 2
            Console.WriteLine("Z's: {0}", namesByInitial['Z'].Count()); // 0, does not throw
        }
    }
}