2024. 2. 14. 17:30ㆍC#
Visual Studio를 통해 C# 프로젝트를 생성하고 스크립트를 생성하면 가장 위에 using 문 세 줄이 나오는데요,
오늘은 이 세 줄의 using문을 참고하여 자료구조의 역사에 대해 알아보겠습니다.
현재 만들고자 하는 프로그램에 적합한 자료구조를 선택하여 코드를 작성합니다.(코드 최적화에 도움)
System에서 Generic Collection까지의 발전 과정을 느껴보세요.
using System;
using System.Collections;
using System.Collections.Generic;
C# 구조 파악 정리글(참고 블로그)
https://vansoft1215.tistory.com/53
1. System 네임스페이스
일반적으로 사용되는 값과 참조 데이터 형식, 이벤트와 이벤트 처리기, 인터페이스, 특성, 예외 처리 등을 정의하는 핵심 클래스 및 기본 클래스가 포함되어 있습니다.
API 문서
클래스간 상하관계 파악 및 세부내용 공부용
https://learn.microsoft.com/ko-kr/dotnet/api/system?view=net-8.0#interfaces
2. 컬렉션(Collection) 클래스
프로그래밍에서 데이터(자료)를 효율적으로 관리하는 것은 아주 중요한 일입니다.
자료구조란, 데이터를 구조적으로 표현하고 구현하는 중요한 알고리즘 입니다.
컬렉션(Collection)은 C#에서 지원하는 자료구조 클래스 입니다.
컬렉션의 종류는 대표적으로 ArrayList, Stack, Queue, Hashtable 등이 있습니다.
ArrayList | |
Stack | |
Queue | |
Hashtable |
컬렉션은 object 형식을 사용하여 데이터를 관리하기 떄문에, 박싱(Boxing)과 언박싱(Unboxing)이 발생합니다.
그래서 컬렉션을 많이 사용하게 되면, 프로그램의 성능 저하가 옵니다.
성능 이유로 현재 C#에서는 컬렉션을 잘 사용하지 않습니다.
using 지시문
using System.Collections;
컬렉션 클래스의 사용
using System;
using System.Collections;
namespace StudyCShap
{
class StudyCollections
{
static void Main()
{
ArrayList list_value = new ArrayList();
Stack stack_value = new Stack();
Queue que_value = new Queue();
Hashtable table_value = new Hashtable();
list_value.Clear();
stack_value.Clear();
que_value.Clear();
table_value.Clear();
for (int i = 0; i < 26; i++)
{
list_value.Add((char)(i + 'A') + "");
stack_value.Push((char)(i + 'A') + "");
que_value.Enqueue((char)(i + 'A') + "");
table_value.Add(i, (char)(i + 'A') + "");
}
Console.WriteLine("요소 개수 : {0}\n", list_value.Count);
Console.WriteLine("요소 개수 : {0}\n", stack_value.Count);
Console.WriteLine("요소 개수 : {0}\n", que_value.Count);
Console.WriteLine("요소 개수 : {0}\n", table_value.Count);
string msg1 = list_value[5] as string;
Console.WriteLine("{0} 요소 개수: {1}\n", msg1, list_value.Count);
string msg2 = stack_value.Pop() as string;
Console.WriteLine("{0} 요소 개수: {1}\n", msg2, stack_value.Count);
string msg3 = que_value.Dequeue() as string;
Console.WriteLine("{0} 요소 개수: {1}\n", msg3, que_value.Count);
string msg4 = table_value[5] as string;
Console.WriteLine("{0} 요소 개수: {1}\n", msg4, table_value.Count);
}
}
}
3. 제네릭 컬렉션(Generic Collection) 클래스
컬렉션의 성능 문제로 인해 대신 사용하는 것이 제네릭 컬렉션 입니다.
제네릭 컬렉션은 데이터 형식을 일반화(generalization)하여 사용하기 때문에 컬렉션에 비해 성능 문제가 적습니다.
제네릭 컬렉션은 List<T>, Dictionary<T>, Stack<T>, Queue<T> 등의 클래스가 있습니다.
API 문서
https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic?view=net-8.0
using 지시문
using System.Collections.Generic;
3.1 List<T> 클래스
List<T> 클래스는 배열 크기를 바꿀 수 있는 가변배열입니다.
기존의 배열은 미리 크기를 정하고 사용해야 하나, List<T>를 사용하게 되면 자유롭게 배열의 크기를 조절할 수 있습니다.
Add, Insert 메소드를 사용하여 데이터를 저장할 수 있고, Remove 메소드를 통해 데이터를 지울 수 있습니다.
속성 | 설명 |
Capacity | 크기를 조정하지 않고 내부 데이터 구조가 보유할 수 있는 전체 요소 수를 가져오거나 설정한다. |
Count | List에 있는 요소의 개수를 가져온다. |
Item[Int32] | 지정한 인덱스에 있는 요소를 가져오거나 설정한다. |
using System;
using System.Collections.Generic;
namespace StudyCShap
{
class LIstExample
{
void ListExample_()
{
List<string> list = new List<string>();
// 동적 추가
list.Add("1번째");
list.Add("2번째");
list.Add("3번째");
list.Add("4번째");
Console.WriteLine(list[1]); // 2번째
Console.WriteLine(list.Capacity); // 4
Console.WriteLine(list.Count); // 4
list.RemoveAt(2); // 1번째 3번째 4번째
list.Remove("4번째"); // 1번째 3번째
list.Insert(0, "새 0번째"); // 새 0번째 1번째 3번째
}
}
}
3.2 Dictionary<T>
Dictionary는 키(Key)와 값(Value)을 한쌍으로 저장하는 자료구조 입니다.
키 값은 유일해야 하며, 키 값에서 값을 찾기 때문에 빠른 검색이 가능합니다.
속성 | 설명 |
Comparer | 사전에 대한 키의 일치 여부를 확인하는 데 사용되는 IEqualityComparer<T>를 가져온다. |
Count | Dictionary<TKey,TValue>에 포함된 키/값 쌍의 수를 가져온다. |
Item[TKey] | 지정된 키와 연결된 값을 가져오거나 설정한다. |
Keys | Dictionary<TKey,TValue>의 키를 포함하는 컬렉션을 가져온다. |
Values | Dictionary<TKey,TValue>의 값을 포함하는 컬렉션을 가져온다. |
using System;
using System.Collections.Generic;
namespace StudyCShap
{
class DictionaryExample
{
void DictionaryExample_()
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(101, "1번째");
dictionary.Add(102, "2번째");
dictionary.Add(103, "3번째");
dictionary.Add(104, "4번째");
foreach (var item in dictionary)
{
Console.Write($"{item.Key} {item.Value}");
// 출력: 101 1번째 102 2번째 103 3번째 104 4번째
}
foreach (var key in dictionary.Keys)
{
Console.Write(key);
// 출력: 101 102 103 104
}
foreach (var value in dictionary.Values)
{
Console.Write(value);
// 출력: 1번째 2번째 3번째 4번째
}
Console.Write($"{dictionary[101]}");
// 출력: 1번째
}
}
}
3.3 Stack<T> 클래스
Stack<T> 클래스는 후입선출(LIFO, Last In First Out) 자료구조 입니다.
후입선출이란 나중에 들어온 데이터가 먼저 출력된다는 뜻입니다.
using System;
using System.Collections.Generic;
namespace StudyCShap
{
class StackExample
{
public void StackExample_()
{
Stack<string> stack = new Stack<string>();
stack.Push("1번째");
stack.Push("2번째");
stack.Push("3번째");
foreach (var item in stack)
{
Console.Write(item); // 3번째 2번째 1번째
}
Console.WriteLine(stack.Peek().ToString()); // 3번째
stack.Pop();
foreach (var item in stack)
{
Console.WriteLine(item); // 2번째 1번째
}
}
}
}
3.4 Queue<T> 클래스
Queue<T> 클래스는 선입선출(FIFO, First In First Out) 자료구조 입니다.
using System;
using System.Collections.Generic;
namespace StudyCShap
{
class QueueExample
{
public void QueueExample_()
{
Queue<string> queue = new Queue<string>();
queue.Enqueue("1번째");
queue.Enqueue("2번째");
queue.Enqueue("3번째");
foreach (var item in queue)
{
Console.WriteLine(item); // 1번째 2번째 3번째
}
Console.WriteLine(queue.Peek()); // 1번째
queue.Dequeue();
foreach (var item in queue)
{
Console.WriteLine(item); // 2번째 3번째
}
}
}
}
참고 블로그
'C#' 카테고리의 다른 글
[C#] 값 형식과 참조 형식의 메모리 저장 방식 차이 (0) | 2024.03.01 |
---|---|
[C#] 인터페이스 (0) | 2024.02.19 |