컬렉션 소개 (Introduction to Collections)
컬렉션은 여러 개의 데이터를 하나의 단위로 관리할 수 있는 구조입니다. C#에는 다양한 컬렉션 클래스가 제공되며, 이러한 클래스들은 System.Collections 및 System.Collections.Generic 네임스페이스에 포함되어 있습니다. 컬렉션은 데이터를 저장, 검색, 관리하는데 사용되며, 배열보다 더 유연하고 강력한 기능을 제공합니다.
배열 (Array)
배열은 동일한 타입의 데이터를 연속된 메모리 공간에 저장하는 자료 구조입니다. 배열은 고정된 크기를 가지며, 인덱스를 통해 요소에 접근할 수 있습니다.
예제: 배열 사용 (Using Arrays)
using System;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 배열 선언 및 초기화 (Declaring and Initializing an Array)
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
// 배열 요소 접근 (Accessing Array Elements)
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
}
}
리스트 (List)
리스트는 가변 크기의 배열로, 요소를 동적으로 추가하거나 제거할 수 있습니다. List<T> 클래스는 제네릭 컬렉션으로, 다양한 타입의 데이터를 저장할 수 있습니다.
예제: 리스트 사용 (Using List)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 리스트 선언 및 초기화 (Declaring and Initializing a List)
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
// 리스트에 요소 추가 (Adding Elements to the List)
names.Add("Dave");
// 리스트 요소 접근 (Accessing List Elements)
foreach (string name in names)
{
Console.WriteLine(name);
}
// 리스트에서 요소 제거 (Removing Elements from the List)
names.Remove("Alice");
Console.WriteLine("After removal:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
}
딕셔너리 (Dictionary)
딕셔너리는 키와 값의 쌍으로 데이터를 저장하는 컬렉션입니다. 각 키는 고유하며, 키를 사용하여 값에 빠르게 접근할 수 있습니다. Dictionary<TKey, TValue> 클래스는 제네릭 컬렉션으로, 다양한 타입의 키와 값을 저장할 수 있습니다.
예제: 딕셔너리 사용 (Using Dictionary)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 딕셔너리 선언 및 초기화 (Declaring and Initializing a Dictionary)
Dictionary<int, string> students = new Dictionary<int, string>
{
{ 1, "Alice" },
{ 2, "Bob" },
{ 3, "Charlie" }
};
// 딕셔너리에 요소 추가 (Adding Elements to the Dictionary)
students.Add(4, "Dave");
// 딕셔너리 요소 접근 (Accessing Dictionary Elements)
foreach (KeyValuePair<int, string> student in students)
{
Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");
}
// 딕셔너리에서 요소 제거 (Removing Elements from the Dictionary)
students.Remove(2);
Console.WriteLine("After removal:");
foreach (KeyValuePair<int, string> student in students)
{
Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");
}
}
}
}
스택 (Stack)
스택은 LIFO(Last-In, First-Out) 구조를 가진 컬렉션입니다. 마지막에 추가된 요소가 가장 먼저 제거됩니다. Stack<T> 클래스는 제네릭 컬렉션으로, 다양한 타입의 데이터를 저장할 수 있습니다.
예제: 스택 사용 (Using Stack)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 스택 선언 및 초기화 (Declaring and Initializing a Stack)
Stack<string> stack = new Stack<string>();
// 스택에 요소 추가 (Pushing Elements onto the Stack)
stack.Push("Alice");
stack.Push("Bob");
stack.Push("Charlie");
// 스택에서 요소 제거 및 접근 (Popping Elements from the Stack)
while (stack.Count > 0)
{
string name = stack.Pop();
Console.WriteLine(name);
}
}
}
}
큐 (Queue)
큐는 FIFO(First-In, First-Out) 구조를 가진 컬렉션입니다. 먼저 추가된 요소가 먼저 제거됩니다. Queue<T> 클래스는 제네릭 컬렉션으로, 다양한 타입의 데이터를 저장할 수 있습니다.
예제: 큐 사용 (Using Queue)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 큐 선언 및 초기화 (Declaring and Initializing a Queue)
Queue<string> queue = new Queue<string>();
// 큐에 요소 추가 (Enqueuing Elements)
queue.Enqueue("Alice");
queue.Enqueue("Bob");
queue.Enqueue("Charlie");
// 큐에서 요소 제거 및 접근 (Dequeuing Elements)
while (queue.Count > 0)
{
string name = queue.Dequeue();
Console.WriteLine(name);
}
}
}
}
해시셋 (HashSet)
해시셋은 중복된 요소를 허용하지 않는 컬렉션입니다. 빠른 조회 성능을 제공합니다. HashSet<T> 클래스는 제네릭 컬렉션으로, 다양한 타입의 데이터를 저장할 수 있습니다.
예제: 해시셋 사용 (Using HashSet)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 해시셋 선언 및 초기화 (Declaring and Initializing a HashSet)
HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5 };
// 해시셋에 요소 추가 (Adding Elements to the HashSet)
numbers.Add(6);
numbers.Add(3); // 중복된 요소는 추가되지 않음
// 해시셋 요소 접근 (Accessing HashSet Elements)
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// 해시셋에서 요소 제거 (Removing Elements from the HashSet)
numbers.Remove(4);
Console.WriteLine("After removal:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
}
컬렉션 종합 예제 (Comprehensive Example of Collections)
using System;
using System.Collections.Generic;
namespace CollectionExample
{
class Program
{
static void Main(string[] args)
{
// 배열 (Array)
int[] array = { 1, 2, 3, 4, 5 };
Console.WriteLine("Array:");
foreach (int item in array)
{
Console.WriteLine(item);
}
// 리스트 (List)
List<string> list = new List<string> { "Alice", "Bob", "Charlie" };
list.Add("Dave");
Console.WriteLine("\nList:");
foreach (string item in list)
{
Console.WriteLine(item);
}
// 딕셔너리 (Dictionary)
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" },
{ 3, "Cherry" }
};
dictionary.Add(4, "Date");
Console.WriteLine("\nDictionary:");
foreach (var item in dictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
// 스택 (Stack)
Stack<string> stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");
stack.Push("Third");
Console.WriteLine("\nStack:");
while (stack.Count > 0)
{
Console.WriteLine(stack.Pop());
}
// 큐 (Queue)
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
Console.WriteLine("\nQueue:");
while (queue.Count > 0)
{
Console.WriteLine(queue.Dequeue());
}
// 해시셋 (HashSet)
HashSet<int> hashSet = new HashSet<int> { 1, 2, 3, 4, 5 };
hashSet.Add(3);
hashSet.Add(6);
Console.WriteLine("\nHashSet:");
foreach (int item in hashSet)
{
Console.WriteLine(item);
}
}
}
}
이 종합 예제는 배열, 리스트, 딕셔너리, 스택, 큐, 해시
셋 등 다양한 컬렉션의 사용법을 보여줍니다. 각 컬렉션의 특징과 사용 방법을 이해하고 상황에 맞게 적절한 컬렉션을 선택하는 것이 중요합니다. C#의 다양한 컬렉션 클래스를 활용하여 효율적인 데이터 관리를 할 수 있습니다.
