C#에서 Stack(스택) 컬렉션에 특정 요소가 포함되어 있는지 확인하려면 Contains() 메서드를 사용하면 됩니다. 이 메서드는 지정한 요소가 스택 안에 존재하면 true를, 존재하지 않으면 false를 반환합니다.
Contains() 메서드란?
Contains()는 System.Collections.Generic 네임스페이스의 Stack<T> 클래스에서 제공하는 메서드로, 스택을 처음부터 끝까지 순차적으로 검색하여 일치하는 요소가 있는지 판별합니다. 값 형식은 값 자체를 비교하고, 참조 형식은 기본적으로 동등성 비교를 수행합니다.
예제 1: 정수형 스택
다음은 정수를 저장하는 스택에서 특정 숫자의 포함 여부를 확인하는 예제입니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(150);
stack.Push(175);
stack.Push(200);
stack.Push(225);
stack.Push(250);
stack.Push(300);
stack.Push(400);
stack.Push(450);
stack.Push(500);
Console.WriteLine("Elements in the Stack:");
foreach(var val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Count of elements in the Stack = " + stack.Count);
Console.WriteLine("Does Stack has the element 400? = " + stack.Contains(400));
}
}
실행 결과
위 코드를 실행하면 다음과 같은 출력이 나타납니다.
Elements in the Stack: 500 450 400 300 250 225 200 175 150 100 Count of elements in the Stack = 10 Does Stack has the element 400? = True
숫자 400이 스택에 존재하기 때문에 Contains(400)은 True를 반환했습니다.
예제 2: 문자열 스택
이번에는 문자열을 저장하는 스택에서 존재하지 않는 요소를 조회해 보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<string> stack = new Stack<string>();
stack.Push("Steve");
stack.Push("Gary");
stack.Push("Stephen");
stack.Push("Nathan");
stack.Push("Katie");
stack.Push("Andy");
stack.Push("David");
stack.Push("Amy");
Console.WriteLine("Elements in the Stack:");
foreach(var val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Count of elements in the Stack = " + stack.Count);
Console.WriteLine("Does Stack has the element Michael? = " + stack.Contains("Michael"));
}
}
실행 결과
위 코드를 실행하면 다음과 같은 출력이 나타납니다.
Elements in the Stack: Amy David Andy Katie Nathan Stephen Gary Steve Count of elements in the Stack = 8 Does Stack has the element Michael? = False
"Michael"이라는 문자열은 스택에 없으므로 Contains("Michael")은 False를 반환했습니다.
정리
C#의 Stack<T>에서 요소 포함 여부를 확인할 때는 Contains() 메서드 하나면 충분합니다. 참고로 이 메서드는 내부적으로 선형 검색을 수행하므로 시간 복잡도는 O(n)입니다. 따라서 대량의 데이터에서 빈번하게 존재 여부를 확인해야 한다면 HashSet<T> 같은 다른 컬렉션을 고려하는 것이 성능 면에서 유리할 수 있습니다.