A-Dyu의 개발 일기장
[C#] 값의 집합을 저장하는 HashSet(해시셋) 클래스 본문
값의 집합을 나타내는 클래스입니다.
집합은 중복 요소가 없고 요소가 특정 순서가 없는 컬렉션입니다.
생성자
생성자는 인자가 없는 생성자와, 집힙을 미리 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
'C#' 카테고리의 다른 글
[C#] 리터럴 (0) | 2025.01.18 |
---|---|
[C#] Enum을 플래그로 사용하기 (0) | 2025.01.18 |
[C#] List를 배열의 특정 부분에 전체 또는 일부 복사하기. (0) | 2024.07.30 |
[C#] C#에서 지원하는 자료구조들 (0) | 2024.07.29 |