Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# List에 요소 추가하는 방법 – Add() 메서드 완벽 정리

C#에서 List<T> 컬렉션에 새로운 요소를 추가하려면 Add() 메서드를 사용합니다. Add()는 전달받은 요소를 리스트의 맨 끝에 추가하며, 내부 용량(capacity)이 부족하면 자동으로 확장되기 때문에 개발자가 크기를 미리 지정할 필요가 없습니다.

List.Add() 메서드 구문

public void Add(T item);

item: 리스트 끝에 추가할 객체입니다. 참조 형식의 경우 null 값도 허용됩니다. 요소가 추가될 때마다 Count 값이 1씩 증가하며, 필요 시 Capacity도 함께 늘어납니다.

예제 1: 문자열 리스트에 요소 추가

아래 예제에서는 List<string>을 생성한 후 Add() 메서드로 여러 문자열을 추가하고, GetEnumerator()로 얻은 열거자(Enumerator)를 통해 각 요소를 순회하며 출력합니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(String[] args) {
      List<String> list = new List<String>();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");

      Console.WriteLine("열거자가 리스트 요소를 순회합니다...");
      List<string>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

출력 결과

열거자가 리스트 요소를 순회합니다...
One
Two
Three
Four
Five
Six
Seven
Eight

예제 2: 정수 리스트에 요소 추가

이번에는 정수(int) 타입의 리스트에 숫자 값을 추가하는 예제입니다. 사용 방식은 동일하며, 제네릭 타입 매개변수만 int로 변경하면 됩니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(50);
      list.Add(100);
      list.Add(150);
      list.Add(200);
      list.Add(250);
      list.Add(500);
      list.Add(750);
      list.Add(1000);
      list.Add(1250);
      list.Add(1500);

      Console.WriteLine("열거자가 리스트 요소를 순회합니다...");
      List<int>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         int res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

출력 결과

열거자가 리스트 요소를 순회합니다...
50
100
150
200
250
500
750
1000
1250
1500

정리

C#의 List<T>에 요소를 추가하는 가장 기본적인 방법은 Add() 메서드를 사용하는 것입니다. Add()는 항상 리스트의 마지막 위치에 요소를 삽입합니다. 만약 특정 인덱스 위치에 요소를 삽입하고 싶다면 Insert(), 다른 컬렉션의 모든 요소를 한 번에 추가하고 싶다면 AddRange() 메서드를 활용하면 됩니다. 이처럼 List<T>는 동적 배열 역할을 하며, 크기 걱정 없이 유연하게 데이터를 관리할 수 있는 강력한 컬렉션입니다.