C#

[C#] Collection / Generic Collection

연향동큰손 2026. 1. 4. 15:35

Collection

Collection은 여러 자료구조를 공통된 인터페이스와 규칙으로 묶어 놓은 자료구조들의 집합이며,

 

.Net 프레임워크에서 비제네릭 컬렉션 클래스를 담당하는 대표적인 네임스페이스이다.

 

Collection 주요 클래스

  • ArrayList : 크기가 가변적인 배열, 인덱스를 통해 데이터에 접근 가능
  • Hashtable : Key-Value 저장
  • Queue : FIFO
  • Stack : LIFO
	// ArrayList 예제
        ArrayList al = new ArrayList();
        al.Add(10);
        al.Add("Hello");

        foreach(var item in al){
            Console.WriteLine(item);
        }

        // Hashtable 예제
        Hashtable table = new Hashtable();

        table["id"] = 1;
        table["name"] = "우현";

        Console.WriteLine("ID: " + table["id"]);
        Console.WriteLine("Name: " + table["name"]);

        // Queue 예제
        Queue queue = new Queue();

        queue.Enqueue(1);
        queue.Enqueue("Hello");

        Console.WriteLine(queue.Dequeue());
        Console.WriteLine(queue.Dequeue());

        // Stack 예제
        Stack stack = new Stack();

        stack.Push(1);
        stack.Push(2);

        Console.WriteLine(stack.Pop());
        Console.WriteLine(stack.Pop());

 

 

Generic Collection

Generic Collection은 Collection과 다르게 데이터 타입을 필수적으로 명시해야 한다.

 

이를 통해 타입 안정성이 확보되며 컴파일 시 타입 검사를 수행해 런타임 오류가 줄어드는 장점을 가져갈 수 있다.

 

또한 박싱과 언박싱의 과정이 이루어지지 않기 때문에 성능이 올라간다.

 

Generic Collection 주요 클래스

  • List<T> : 가변 크기 배열, 인덱스로 데이터에 접근 가능
추가 Add(T item) 맨 뒤에 추가
삽입 Insert(int index, T item) 중간 삽입
삭제 Remove(T item) 값으로 삭제
삭제 RemoveAt(int index) 인덱스로 삭제
조회 list[index] 인덱스 접근
검색 Contains(T item) 포함 여부
검색 IndexOf(T item) 인덱스 반환
개수 Count 요소 수
초기화 Clear() 전체 삭제

 

 

  • Dictionary<TKey, TValue> :  Key-Value 저장
추가 Add(key, value) Key-Value 추가
추가/수정 dict[key] = value 없으면 추가, 있으면 수정
조회 dict[key] Key로 값 조회
삭제 Remove(key) Key 삭제
검사 ContainsKey(key) Key 존재 여부
검사 ContainsValue(value) Value 존재 여부
전체 키 Keys Key 컬렉션
전체 값 Values Value 컬렉션
개수 Count 쌍 개수

 

 

  • Queue<T>, Stack<T> :  Collection의 큐,스택과 동일한 저장방식, 다만 자료형을 미리 명시 해줘야 함.

Queue<T>

추가 Enqueue(T item) 뒤에 추가
제거 Dequeue() 앞에서 제거
조회 Peek() 제거 없이 조회
개수 Count 요소 수
초기화 Clear() 전체 삭제

 

Stack<T>

추가 Push(T item) 맨 위에 추가
제거 Pop() 맨 위 제거
조회 Peek() 제거 없이 조회
개수 Count 요소 수
초기화 Clear() 전체 삭제

 

 

  • HashSet<T> :  중복 데이터 저장 허용X, 데이터 존재 여부를 빠르게 검사 가능
추가 Add(T item) 중복 시 false
삭제 Remove(T item) 값 제거
검사 Contains(T item) 존재 여부
집합 UnionWith() 합집합
집합 IntersectWith() 교집합
집합 ExceptWith() 차집합
개수 Count 요소 수
초기화 Clear() 전체 삭제

 

 

  • System.Collections.SortedList : 키값을 기준으로 정렬된 상태를 유지하며 저장(Add를 통해 데이터를 추가하면 자동으로 정렬 수행)

'C#' 카테고리의 다른 글

[C#] LINQ(데이터 쿼리)  (0) 2026.02.19
스레딩  (0) 2026.01.13
BCL  (0) 2026.01.10
[C#] 대리자(delegate)  (0) 2026.01.08