728x90
반응형

List부터 Dictionary, LINQ까지!

C#을 실무에서 쓰려면 컬렉션(Collection)LINQ(Language Integrated Query) 는 꼭 알아야 합니다.
이번 글에서는 List, Dictionary 사용법과 함께 LINQ를 이용해 데이터를 쉽게 다루는 방법까지 정리해보겠습니다.


1. 컬렉션 (Collection) 기초

컬렉션은 여러 데이터를 묶어 관리하는 자료구조입니다.

 List - 가변 크기 배열

List<string> fruits = new List<string>();
fruits.Add("사과");
fruits.Add("바나나");
fruits.Add("포도");

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

 Dictionary<TKey, TValue> - 키-값 쌍 저장

Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 90;
scores["Bob"] = 85;

foreach (var pair in scores)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

 배열과 List 차이

항목 배열 (Array) List

크기 변경 불가능 가능 (Add/Remove 지원)
선언 int[] arr = new int[5]; List<int> list = new List<int>();
사용 용도 고정 크기 데이터 유동적 데이터 관리

2. LINQ 기초

LINQ는 C#에 통합된 쿼리 기능입니다.
SQL처럼 데이터를 필터링, 정렬, 변환할 수 있게 해줍니다.

복잡한 for문 없이 데이터를 간단하게 조작할 수 있습니다.

 LINQ 기본 사용법

using System.Linq;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };

// 짝수만 추출
var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var n in evenNumbers)
{
    Console.WriteLine(n);  // 2, 4, 6
}

 Select (변환)

var squares = numbers.Select(n => n * n);

foreach (var n in squares)
{
    Console.WriteLine(n);  // 1, 4, 9, 16, 25, 36
}

 OrderBy (정렬)

List<string> names = new List<string> { "Charlie", "Alice", "Bob" };
var sortedNames = names.OrderBy(name => name);

foreach (var name in sortedNames)
{
    Console.WriteLine(name);  // Alice, Bob, Charlie
}

 FirstOrDefault (처음 찾기)

int firstEven = numbers.FirstOrDefault(n => n % 2 == 0);
Console.WriteLine(firstEven);  // 2

3. LINQ 메서드 정리

메서드 설명

Where 조건에 맞는 요소 필터링
Select 요소 변환
OrderBy, OrderByDescending 정렬
FirstOrDefault 첫 번째 요소 가져오기 (없으면 기본값)
Any 조건을 만족하는 요소가 있는지 확인
Count 요소 개수 세기

 

이번 글에서는 C#의 필수 컬렉션(List, Dictionary) 사용법과, 데이터를 간결하게 다루는 LINQ 기초를 정리했습니다.

  • List: 유동적 크기의 순차 자료구조
  • Dictionary: 키-값 쌍 저장
  • LINQ: 데이터를 쉽고 깔끔하게 필터링, 변환, 정렬하는 방법

 

728x90
반응형

+ Recent posts