C#
[C#] 값의 집합을 저장하는 HashSet(해시셋) 클래스
ADyu
2024. 7. 29. 00:51
값의 집합을 나타내는 클래스입니다.
집합은 중복 요소가 없고 요소가 특정 순서가 없는 컬렉션입니다.
생성자
생성자는 인자가 없는 생성자와, 집힙을 미리 Array로 초기화할 수 있습니다.
HashSet<int> hashSet1 = new HashSet<int>(); //빈 집합 생성
int[] array = { 1, 2, 3, 1, 4 };
HashSet<int> hashSet2 = new HashSet<int>(array); //생성 시 요소를 추가함
요소 추가/제거
Add메서드를 사용해 집합 요소를 추가하고, Remove메서드를 사용해 요소를 제거할 수 있습니다.
hashSet1.Add(1);
hashSet1.Remove(1);
값이 포함되어 있는지
hashSet1.Contains(1);//값이 포함되어 있는지
집합 메서드
HashSet<int> set = new HashSet<int> { 2, 3, 4 };
hashSet1.UnionWith(set); //합집합
hashSet1.IntersectWith(set); //교집합
hashSet1.ExceptWith(set); //차집합
개수
int cnt = numbers.Count;//집합 요소의 개수
비우기
hashSet1.Clear();
자세한 건 공식 API에서...
https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.hashset-1?view=net-8.0