Post

[C#] 배열과 컬렉션

[C#] 배열과 컬렉션

배열과 컬렉션


배열

동일한 자료형의 값들이 연속적으로 저장되는 자료 구조

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 배열 선언
데이터_유형[] 배열_이름;

// 배열 초기화
배열_이름 = new 데이터_유형[크기];

// 배열을 한 줄로 선언 및 초기화
데이터_유형[] 배열_이름 = new 데이터_유형[크기];

// 배열 요소에 접근
배열_이름[인덱스] = ;
 = 배열_이름[인덱스];

int[] array1 = new int[5];       // 크기가 5인 int형 배열 선언
string[] array2 = new string[3]; // 크기가 3인 string형 배열 선언
int num = 0;

// 배열 초기화
array1[0] = 1;
array1[1] = 2;
array1[2] = 3;
array1[3] = 4;
array1[4] = 5;

num = array1[0];

컬렉션

자료를 모아 놓은 데이터 구조를 의미하며, 배열과 비슷한 자료구조이지만 크기가 가변적이다.

  • 1) List
    • List는 가변적인 크기를 갖는 배열
    • List를 생성할 때는 List에 담을 자료형을 지정
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      
      List<int> numbers = new List<int>(); // 빈 리스트 생성
      numbers.Add(1); // 리스트에 데이터 추가
      numbers.Add(2);
      numbers.Add(3);
      numbers.Remove(2); // 리스트에서 데이터 삭제
          
      foreach(int number in numbers) // 리스트 데이터 출력
      {
          Console.WriteLine(number);
      }
      
  • 2) Dictionary
    • 딕셔너리(Dictionary)는 키와 값으로 구성된 데이터를 저장
    • 딕셔너리는 중복된 키를 가질 수 없으며, 키와 값의 쌍을 이루어 데이터를 저장
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
      using System.Collections.Generic;
        
      Dictionary<string, int> scores = new Dictionary<string, int>(); // 빈 딕셔너리 생성
      scores.Add("Alice", 100); // 딕셔너리에 데이터 추가
      scores.Add("Bob", 80);
      scores.Add("Charlie", 90);
      scores.Remove("Bob"); // 딕셔너리에서 데이터 삭제
        
      foreach(KeyValuePair<string, int> pair in scores) // 딕셔너리 데이터 출력
      {
          Console.WriteLine(pair.Key + ": " + pair.Value);
      }
    
  • 3) Stack
    • Stack은 후입선출(LIFO) 구조를 가진 자료 구조
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
      Stack<int> stack1 = new Stack<int>();  // int형 Stack 선언
        
      // Stack에 요소 추가
      stack1.Push(1);
      stack1.Push(2);
      stack1.Push(3);
        
      // Stack에서 요소 가져오기
      int value = stack1.Pop(); // value = 3 (마지막에 추가된 요소)
    
  • 4) Queue
    • Queue는 선입선출(FIFO) 구조를 가진 자료 구조
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
      Queue<int> queue1 = new Queue<int>(); // int형 Queue 선언
        
      // Queue에 요소 추가
      queue1.Enqueue(1);
      queue1.Enqueue(2);
      queue1.Enqueue(3);
        
      // Queue에서 요소 가져오기
      int value = queue1.Dequeue(); // value = 1 (가장 먼저 추가된 요소)
    
  • 5) HashSet
    • HashSet은 중복되지 않은 요소들로 이루어진 집합
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
      HashSet<int> set1 = new HashSet<int>();  // int형 HashSet 선언
        
      // HashSet에 요소 추가
      set1.Add(1);
      set1.Add(2);
      set1.Add(3);
        
      // HashSet에서 요소 가져오기
      foreach (int element in set1)
      {
          Console.WriteLine(element);
      }
    
This post is licensed under CC BY 4.0 by the author.