C# 기초
C# Lists and Dictionaries
When you need a collection that grows, use List<T>; when you look things up by key, use Dictionary<TKey, TValue>.
배울 내용
- List<T> Add, Remove and indexing
- Dictionary<TKey, TValue> and TryGetValue
- Why generic collections are type-safe
Dictionary<string, int> scores
"Ada"95"Lin"88"Grace"92 (added later)scores.TryGetValue("Grace", out int score) → 92
Ordered values or keyed values
길이가 고정된 배열과 달리 List<T>와 Dictionary<TKey, TValue> 같은 제네릭 컬렉션은 데이터를 추가하면 자동으로 커집니다. 꺾쇠괄호 안의 내용은 저장할 타입을 나타내므로, 컴파일러가 잘못된 타입의 값이 들어가지 않도록 보장합니다.
Dictionary scores는 각 사람의 점수를 이름을 키로 저장하며, scores["Grace"] = 92 문은 새 키-값 쌍을 추가합니다. TryGetValue 메서드는 키로 값을 찾고, 키가 없으면 오류를 일으키는 대신 false를 돌려줍니다. 찾은 값은 out int score 변수로 나오며 92가 출력됩니다.
핵심 포인트
- List<T> keeps items in order and grows automatically.
- Dictionary maps unique keys to values with fast lookup.
- TryGetValue checks and reads in one step, without exceptions.
동작 원리 보기
버튼으로 리스트를 바꾸고 인덱스가 갱신되는 모습을 보세요. start와 stop을 움직이면 슬라이스가 어떤 항목을 가져가는지 알 수 있습니다.
실행 가능한 C# 예제
C#
Program.cs
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var scores = new Dictionary<string, int> { ["Ada"] = 95, ["Lin"] = 88 };
scores["Grace"] = 92;
if (scores.TryGetValue("Grace", out int score))
Console.WriteLine(score);
}
}
92디버거로 연습하기
중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지