C#

배열과 컬렉션(Collection)

잼잼재미 2023. 11. 7. 11:11

배열


 - 동일한 자료형의 값들이 연속적으로 저장되는 자료 구조
 - 선언된 크기만큼 공간을 메모리에 할당받음

 - 최초 선언하는 시점에서 크기를 미리 정해야 함

 

int[] array = new int[3];
array[0] = 3;
array[1] = 5;
array[2] = 2;

int[] itemPrices = {100, 200, 300, 400, 500}; // 배열 생성, 초기화를 한줄로

 

 

최대값, 최소값, 합계, 평균

using System;
using System.Linq;

int[] test_arr = { 1, 2, 3, 4, 5 };

Console.WriteLine(test_arr.Max());	// 5 출력
Console.WriteLine(test_arr.Min());	// 1 출력
Console.WriteLine(test_arr.Sum());	// 15 출력
Console.WriteLine(test_arr.Average());	// 3 출력

 

 

정렬

using System;

int[] itemPrices = {100, 200, 300, 400, 500};

Array.Sort(itemPrices); // 오름차순으로 정렬 {100, 200, 300, 400, 500};
Array.Reverse(itemPrices); // 오름차순 -> 내림차순 {500, 400, 300, 200, 100};

 

 

다차원배열


 - 여러 개의 배열을 하나로 묶어 놓은 배열
 - 행과 열로 이루어진 표 형태와 같은 구조
 - 2차원, 3차원 등의 형태의 배열을 의미
 - 복잡한 데이터 구조를 효율적으로 관리

 - 3차원배열부터는 잘 사용하지 않음

 

 

int[,] array2 = new int [2, 3]; // 2행 3열의 int형 2차원 배열 선언
int[,,] array3 = new int[2, 3, 4]; 

// 2차원배열 맵구현
int[,] map = new int[5, 5]
                {
                    { 1, 1, 1, 1, 1 },
                    { 1, 0, 0, 0, 1 },
                    { 1, 0, 1, 0, 1 },
                    { 1, 0, 0, 0, 1 },
                    { 1, 1, 1, 1, 1 }
                };

            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    if (map[i, j] == 1)
                    {
                        Console.Write("■ ");
                    }
                    else
                    {
                        Console.Write("□ ");
                    }
                }
                Console.WriteLine();
            }

 

 

 

2차원배열의 길이


int[,] answer = new int[5, 3];

answer.GetLength(0);	// 행의 길이 : 5
answer.GetLength(1);	// 열의 길이 : 3
Console.Write(answer.Length);	// 전체 길이 : 15

* C# 에서는 Length는 배열의 전체 길이를 나타냄 

* C# 에서는 행과 열의 길이는 GetLength를 사용해야 함

 

 

컬렉션(Collection)


 - 배열과 비슷한 자료 구조
 - 배열과는 다르게 크기가 가변적

 - System.Collections.Generic 네임스페이스 추가하여 사용

 

 

1. List


 - 가변적인 크기를 갖는 배열

 - List의 원소의 숫자는 Length 대신 Count 사용

 - 컬렉션 중 가장 많이 사용

 - C#에서 리스트와 연결리스트는 별개임, 리스트는 내부적으로 배열로 존재함 (동적배열)

 

 

데이터 추가, 삭제

using System.Collections.Generic;

List<int> numbers = new List<int>();

// 데이터 추가
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

// 데이터 삭제
numbers.Remove(2); // 2를 삭제하고 1, 3이 연결됨
numbers.RemoveAt(1); // numbers[1], 3을 삭제
numbers.RemoveRange(1, 3);	// numbers[1] 부터 총 3개 삭제

// 데이터 전체 삭제
numbers.Clear();	// 데이터 모든 내용 삭제

 

 

최대값, 최소값

using System.Collections.Generic;
using System.Linq;	// Max, Min 사용

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

Console.WriteLine(numbers.Max());	// 최대값, 3 출력
Console.WriteLine(numbers.Min());	// 최소값, 1 출력

 

 

검색

using System.Collections.Generic;

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

Console.WriteLine(numbers.Contatins(3));	// 리스트에 해당 값 있는지 확인, true 출력

 

 

중복 제거

using System.Collections.Generic;
using System.Linq;

List<int> numbers = new List<int>(); // 빈 List 생성
numbers.Add(3);
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(1);

List<int> numbers2 = new List<int>();

numbers2 = numbers.Distinct().ToList();

foreach(int number in numbers2)
{
	Console.WriteLine(number);	// 3, 1, 2 출력
}

 

 

정렬

using System.Collections.Generic;
using System;	// Array.Sort 사용

List<int> numbers = new List<int>(); // 빈 List 생성
numbers.Add(3);
numbers.Add(1);
numbers.Add(2);

numbers.Sort();	// 오름차순 정렬
foreach(int number in numbers)
{
	Console.WriteLine(number);	// 1, 2, 3 출력
}

numbers.Reverse();	// 내림차순 정렬
foreach(int number in numbers)
{
	Console.WriteLine(number);	// 3, 2, 1 출력
}

 

 

데이터 확인

using System.Collections.Generic;

 public List<string> myList = new List<string>(); // 예시로 string 타입의 리스트를 사용합니다.

void Start()
{
    // 리스트에 데이터 추가
    myList.Add("Apple");
    myList.Add("Banana");

    // 데이터 확인
    if (myList.Contains("Apple"))
    {
        Debug.Log("리스트 안에 Apple이 있습니다.");
    }
    else
    {
        Debug.Log("리스트 안에 Apple이 없습니다.");
    }
}

 

 

2. Dictionary


 - 키와 값으로 구성된 데이터를 저장
 - 중복된 키를 가질 수 없으며, 키와 값의 쌍을 이루어 데이터를 저장

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"); // 해당 Key 값의 데이터 삭제

foreach(KeyValuePair<string, int> pair in scores)
{
	Console.WriteLine(pair.Key + ": " + pair.Value);
}

Console.WriteLine(scores["Alice"]); // 100 출력

scores.ContainsKey("Alice");	// Key가 있는지 확인, true

int maxNum = scores.Values.Max(); // 가장 큰 Value 값, 100
int minNum = scores.Values.Min(); // 가장 작은 Value 값, 80

// Key, Value 값을 List로 나타내기
List<string> list = new List<string>(scores.Keys);
List<int> list = new List<int>(scores.Values);

 

 

3. Stack


 - 후입선출(LIFO) 구조를 가진 자료 구조 (나중에 들어온 것이 먼저 나감)

using System.Collections.Generic;

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


 - 선입선출(FIFO) 구조를 가진 자료 구조 (먼저 들어온 것이 먼저 나감)

using System.Collections.Generic;

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


 - 중복되지 않은 요소들로 이루어진 집합

using System.Collections.Generic;

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);
}

 

 

5. 연결리스트 (Linked List)


- 노드로 이루어짐

- 각각의 노드는 데이터를 가지고 다음 노드를 가리킴

-  삽입 및 삭제가 빠르지만 검색은 느릴 수 있음

 

 

using System.Collections.Generic;

LinkedList<int> number = new LinkedList<int>();
number.AddFirst(10); //10
number.AddLast(20); //10, 20
number.AddLast(30); //10, 20, 30
number.AddFirst(9); //9, 10, 20, 30
 
//노드 찾기
LinkedListNode<int> nodeTemp = number.Find(20);
 
number.AddAfter(nodeTemp, 21);
number.AddBefore(nodeTemp, 19);
 
//삭제
number.Remove(10);
 
//검색
for(var node = number.First; node != null; node = node.Next)
{
	Console.WriteLine(node.Value);
}

 

 

배열 <-> List


List -> 배열


using System.Linq;

List<Test> testList = new List<Test>();
Test test = new Test();

test.name = "aaa";
test.weight = 50.3;
testList.Add(test);

test.name = "bbb";
test.weight = 77.7;
testList.Add(test);

test.name = "ccc";
test.weight = 65.3;
testList.Add(test);

Test[] testArray = testList.ToArray();

 

 

배열 -> List


using System.Linq;

Test[] testArray = new Test[3];
Test test = new Test();

test.name = "aaa";
test.weight = 50.3;
testArray[0] = test;

test.name = "bbb";
test.weight = 77.7;
testArray[1] = test;

test.name = "ccc";
test.weight = 65.3;
testArray[2] = test;

List<Test> testList = testArray.ToList();

 

 

배열과 List 비교


 - 리스트만 무분별하게 사용하면 안됨
 - 데이터의 크기와 사용 목적을 고려해서 배열과 리스트 중 적절한 것을 선택해야 함

  List 배열
길이 동적으로 변함 고정
메모리 동적이며 무작위, 메모리 배열보다 많이 차지 정적이며 연속적, 효율적인 메모리
활용 요소의 추가/삭제가 필요할 때 요소가 변경 가능성 없을 때
속도 느림 빠름
메모리 관리 메모리 낭비가 없음 메모리 낭비 발생

 

 

List의 단점


1. 리스트는 동적으로 크기를 조정하기 때문에 배열보다 많은 메모리를 사용
2. 리스트에서는 특정 인덱스의 데이터를 찾기 위해 연결된 노드를 모두 순회하기 때문에 배열보다 느림
3. 데이터 추가, 삭제가 배열보다 간편하지만 코드 복잡도가 증가

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

접근 제한자 (public, private, protected)  (0) 2023.11.08
객체지향 프로그래밍의 특징  (0) 2023.11.08
Random  (0) 2023.11.07
do-while문  (0) 2023.11.07
char 과 string 비교  (0) 2023.11.07