dev/asp.net, c#

[c#] Dictionary 와 LookUp 차이점

코딩for 2022. 11. 17. 17:57
반응형

 

Dictionary 와 LookUp 비교

  Lookup Dictionary
네임스페이스 System.Linq System.Collections.Generic
인터페이스 ILookup IDictionary

 

생성자 유무
  • LookUp : 없음
  • Dcitionary : Dictionary<TKey,TValue> 

* lookup은 생성자가 없어 객체 생성시 오류 발생

 

 

Key 값의 고유 여부

Dictionary 타입은 Key 가 고유하기 때문에 중복 key 등록이 불가하나 LookUp 은 동일키에 중복 데이터 추가가 가능하다.

List<Student> students = new List<Student>
{
    new Student{grade = 3, name = "Tom", scores = new int[] {60, 80} },     
    new Student{grade = 3, name = "Brian" , scores = new int[] {50, 70} },  
    new Student{grade = 4, name = "Chris" , scores = new int[] {80, 80}},   
    new Student{grade = 5, name = "James" , scores = new int[] {100, 100} },
};

var lookup = students.ToLookup(student => student.grade, student => student.grade + ":" + student.name);

* LookUp에는 위 결과과 같이 Key 가 3인 값이 중복으로 등록되나 Dictionary 는 키 중복이 불가하기때문에 Exception 발생하게 된다.

key-value 매핑구조

 

KeyNotFoundException 발생
List<Teacher> teachers = new List<Teacher>
{
    new Teacher{grade = 3, name = "Miss Christina" },
    new Teacher{grade = 4, name = "Mr. Tayler" },
    new Teacher{grade = 6, name = "Mr. Jone" },
    new Teacher{grade = 5, name = "James" },
};

var lookup = teachers.ToLookup(teacher => teacher.grade, teacher => teacher.grade + ":" + teacher.name);
Console.WriteLine(lookup[3]);
Console.WriteLine(lookup[10]);

var teacher = teachers.ToDictionary(teacher => teacher.grade);
Console.WriteLine(teacher[10]);

* LookUp 은 없는 키에 대한 조회를 할 경우 Empty 를 리턴하며 Exception 이 발생하지 않지만

   Dictionary는  KeyNotFoundException 예외가 발생하다.

 

 

데이터 추가 삭제
  • LookUp : 불가
  • Dcitionary : 가능(Add, Remove 메서드 존재)
ILookUp Interface 정보
namespace System.Linq
{
    //
    // 요약:
    //     Defines an indexer, size property, and Boolean search method for data structures
    //     that map keys to System.Collections.Generic.IEnumerable`1 sequences of values.
    //
    // 형식 매개 변수:
    //   TKey:
    //     The type of the keys in the System.Linq.ILookup`2.
    //
    //   TElement:
    //     The type of the elements in the System.Collections.Generic.IEnumerable`1 sequences
    //     that make up the values in the System.Linq.ILookup`2.
    [DefaultMember("Item")]
    public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, IEnumerable
    {
        //
        // 요약:
        //     Gets the System.Collections.Generic.IEnumerable`1 sequence of values indexed
        //     by a specified key.
        //
        // 매개 변수:
        //   key:
        //     The key of the desired sequence of values.
        //
        // 반환 값:
        //     The System.Collections.Generic.IEnumerable`1 sequence of values indexed by the
        //     specified key.
        IEnumerable<TElement> this[TKey key] { get; }

        //
        // 요약:
        //     Gets the number of key/value collection pairs in the System.Linq.ILookup`2.
        //
        // 반환 값:
        //     The number of key/value collection pairs in the System.Linq.ILookup`2.
        int Count { get; }

        //
        // 요약:
        //     Determines whether a specified key exists in the System.Linq.ILookup`2.
        //
        // 매개 변수:
        //   key:
        //     The key to search for in the System.Linq.ILookup`2.
        //
        // 반환 값:
        //     true if key is in the System.Linq.ILookup`2; otherwise, false.
        bool Contains(TKey key);
    }
}
IDictionary Interface 정보
namespace System.Collections.Generic
{
    //
    // 요약:
    //     Represents a generic collection of key/value pairs.
    //
    // 형식 매개 변수:
    //   TKey:
    //     The type of keys in the dictionary.
    //
    //   TValue:
    //     The type of values in the dictionary.
    [DefaultMember("Item")]
    public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TKey : notnull
    {
        //
        // 요약:
        //     Gets or sets the element with the specified key.
        //
        // 매개 변수:
        //   key:
        //     The key of the element to get or set.
        //
        // 반환 값:
        //     The element with the specified key.
        //
        // 예외:
        //   T:System.ArgumentNullException:
        //     key is null.
        //
        //   T:System.Collections.Generic.KeyNotFoundException:
        //     The property is retrieved and key is not found.
        //
        //   T:System.NotSupportedException:
        //     The property is set and the System.Collections.Generic.IDictionary`2 is read-only.
        TValue this[TKey key] { get; set; }

        //
        // 요약:
        //     Gets an System.Collections.Generic.ICollection`1 containing the keys of the System.Collections.Generic.IDictionary`2.
        //
        // 반환 값:
        //     An System.Collections.Generic.ICollection`1 containing the keys of the object
        //     that implements System.Collections.Generic.IDictionary`2.
        ICollection<TKey> Keys { get; }
        //
        // 요약:
        //     Gets an System.Collections.Generic.ICollection`1 containing the values in the
        //     System.Collections.Generic.IDictionary`2.
        //
        // 반환 값:
        //     An System.Collections.Generic.ICollection`1 containing the values in the object
        //     that implements System.Collections.Generic.IDictionary`2.
        ICollection<TValue> Values { get; }

        //
        // 요약:
        //     Adds an element with the provided key and value to the System.Collections.Generic.IDictionary`2.
        //
        // 매개 변수:
        //   key:
        //     The object to use as the key of the element to add.
        //
        //   value:
        //     The object to use as the value of the element to add.
        //
        // 예외:
        //   T:System.ArgumentNullException:
        //     key is null.
        //
        //   T:System.ArgumentException:
        //     An element with the same key already exists in the System.Collections.Generic.IDictionary`2.
        //
        //   T:System.NotSupportedException:
        //     The System.Collections.Generic.IDictionary`2 is read-only.
        void Add(TKey key, TValue value);
        //
        // 요약:
        //     Determines whether the System.Collections.Generic.IDictionary`2 contains an element
        //     with the specified key.
        //
        // 매개 변수:
        //   key:
        //     The key to locate in the System.Collections.Generic.IDictionary`2.
        //
        // 반환 값:
        //     true if the System.Collections.Generic.IDictionary`2 contains an element with
        //     the key; otherwise, false.
        //
        // 예외:
        //   T:System.ArgumentNullException:
        //     key is null.
        bool ContainsKey(TKey key);
        //
        // 요약:
        //     Removes the element with the specified key from the System.Collections.Generic.IDictionary`2.
        //
        // 매개 변수:
        //   key:
        //     The key of the element to remove.
        //
        // 반환 값:
        //     true if the element is successfully removed; otherwise, false. This method also
        //     returns false if key was not found in the original System.Collections.Generic.IDictionary`2.
        //
        // 예외:
        //   T:System.ArgumentNullException:
        //     key is null.
        //
        //   T:System.NotSupportedException:
        //     The System.Collections.Generic.IDictionary`2 is read-only.
        bool Remove(TKey key);
        //
        // 요약:
        //     Gets the value associated with the specified key.
        //
        // 매개 변수:
        //   key:
        //     The key whose value to get.
        //
        //   value:
        //     When this method returns, the value associated with the specified key, if the
        //     key is found; otherwise, the default value for the type of the value parameter.
        //     This parameter is passed uninitialized.
        //
        // 반환 값:
        //     true if the object that implements System.Collections.Generic.IDictionary`2 contains
        //     an element with the specified key; otherwise, false.
        //
        // 예외:
        //   T:System.ArgumentNullException:
        //     key is null.
        bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);
    }
}

 

 

 

참고

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.dictionary-2?view=net-7.0 

https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.lookup-2?view=net-7.0 

 

반응형