C#에서 Collection<T>에 포함된 요소의 개수를 확인하려면 Count 속성을 사용하면 됩니다. Count 속성은 컬렉션에 실제로 들어 있는 요소의 총 개수를 정수(int) 형태로 반환하며, 읽기 전용이므로 값을 직접 변경할 수는 없습니다.
아래 예제를 통해 문자열과 정수를 저장하는 컬렉션에서 요소 개수를 구하는 방법을 살펴보겠습니다.
예제 1: 문자열 컬렉션의 요소 개수 구하기
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("요소 개수 = " + col.Count);
Console.WriteLine("컬렉션 순회 중...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}실행 결과
요소 개수 = 9 컬렉션 순회 중... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
위 코드에서는 9개의 이름을 추가한 뒤 col.Count로 전체 요소 수를 출력했습니다. 또한 GetEnumerator() 메서드를 사용해 열거자(Enumerator)를 얻고, MoveNext()와 Current를 이용해 컬렉션의 모든 요소를 하나씩 순회하며 출력했습니다.
예제 2: 정수 컬렉션에서 Count, Contains, Clear 활용하기
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<int> col = new Collection<int>();
col.Add(10);
col.Add(20);
col.Add(30);
col.Add(40);
col.Add(50);
col.Add(60);
col.Add(70);
col.Add(80);
Console.WriteLine("컬렉션의 요소들...");
foreach(int val in col) {
Console.WriteLine(val);
}
Console.WriteLine("컬렉션에 70이 포함되어 있는가? = " + col.Contains(70));
Console.WriteLine("요소 개수 = " + col.Count);
col.Clear();
Console.WriteLine("초기화 후 요소 개수 = " + col.Count);
}
}실행 결과
컬렉션의 요소들... 10 20 30 40 50 60 70 80 컬렉션에 70이 포함되어 있는가? = True 요소 개수 = 8 초기화 후 요소 개수 = 0
주요 내용 정리
- Count: 컬렉션에 현재 포함된 요소의 총 개수를 반환합니다.
- Contains(T): 특정 요소가 컬렉션에 존재하는지 여부를 true/false로 반환합니다.
- Clear(): 컬렉션의 모든 요소를 제거하며, 호출 후 Count 값은 0이 됩니다.
- foreach 문: GetEnumerator()를 명시적으로 호출하지 않고도 간결하게 컬렉션을 순회할 수 있습니다.
이처럼 C#의 Collection<T> 클래스는 Count 속성만으로도 손쉽게 요소 개수를 파악할 수 있으며, Contains나 Clear 같은 편리한 메서드들과 함께 활용하면 컬렉션을 효율적으로 관리할 수 있습니다.