본문 바로가기
개발/C#

유니티 C# 해시셋 HashSet 사용법 예시 간단 구현

by SPNK 2023. 10. 20.
반응형

HashSet

고유한 요소 집합을 저장하는 컬렉션입니다. 즉, 중복 값을 허용하지 않습니다.

 

  • 생성
HashSet<int> numbers = new HashSet<int>();

 

  • 요소 추가
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(1); // 1은 추가되지 않음. (중복됨)

 

  • 요소 제거
numbers.Remove(2);

 

  • 개수 확인
int count = numbers.Count;

 

  • 루프 사용
foreach (int number in numbers)
{

}

 

  • 해쉬 삭제
numbers.Clear();

 

  • 합집합, 교집합, 차집합
HashSet<int> otherSet = new HashSet<int> { 2, 3, 4 };

numbers.UnionWith(otherSet); // 다른 집합의 요소를 숫자에 추가합니다
numbers.IntersectWith(otherSet); // 공통 요소만 유지합니다
numbers.ExceptWith(otherSet); // 다른 집합에 있는 요소를 제거합니다

 

  • HashSet 생성자
int[] array = { 1, 2, 3, 1, 4 };
HashSet<int> uniqueNumbers = new HashSet<int>(array);
반응형

댓글