728x90
C#에서 HashSet<T>는 중복되지 않는 요소를 저장하는 컬렉션입니다. HashSet<T>는 해시 테이블을 사용하여 요소를 저장하기 때문에, 요소를 빠르게 검색할 수 있습니다.
HashSet<T>의 선언
HashSet<T>는 다음과 같이 선언할 수 있습니다.
C#
HashSet<T> set;
여기서 T는 HashSet<T>에 저장할 요소의 형식입니다.
HashSet<T>의 초기화
HashSet<T>는 다음과 같이 초기화할 수 있습니다.
set = new HashSet<T>();
또는, 다음과 같이 요소를 사용하여 초기화할 수 있습니다.
set = new HashSet<T>(new List<T>());
HashSet<T>에 요소 추가
HashSet<T>에 요소를 추가하려면 Add() 메서드를 사용합니다.
set.Add(new T());
또는, 다음과 같이 리터럴을 사용하여 요소를 추가할 수 있습니다.
set.Add(1);
HashSet<T>에서 요소 제거
HashSet<T>에서 요소를 제거하려면 Remove() 메서드를 사용합니다.
set.Remove(new T());
또는, 다음과 같이 리터럴을 사용하여 요소를 제거할 수 있습니다.
set.Remove(1);
HashSet<T>의 요소 검색
HashSet<T>에서 요소를 검색하려면 Contains() 메서드를 사용합니다.
bool contains = set.Contains(new T());
또는, 다음과 같이 리터럴을 사용하여 요소를 검색할 수 있습니다.
bool contains = set.Contains(1);
HashSet<T>의 요소 순회
HashSet<T>의 요소를 순회하려면 foreach 루프를 사용할 수 있습니다.
foreach (T item in set) {
// ...
}
HashSet<T>의 메서드
HashSet<T>는 다음과 같은 메서드를 제공합니다.
- Add(T item): 요소를 추가합니다.
- Remove(T item): 요소를 제거합니다.
- Contains(T item): 요소가 포함되어 있는지 확인합니다.
- Count: 요소의 개수를 반환합니다.
- IsEmpty: 컬렉션이 비어 있는지 확인합니다.
- ToArray(): T[]: 요소를 배열로 반환합니다.
HashSet<T>의 예제
다음은 HashSet<T>를 사용하는 예제입니다.
using System;
public class Example
{
public static void Main(string[] args)
{
// HashSet<T>를 생성합니다.
HashSet<int> numbers = new HashSet<int>();
// 요소를 추가합니다.
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// 요소를 검색합니다.
bool contains = numbers.Contains(2);
Console.WriteLine(contains); // true
// 요소를 제거합니다.
numbers.Remove(2);
// 요소를 순회합니다.
foreach (int number in numbers) {
Console.WriteLine(number);
} // 1 3
// 요소의 개수를 확인합니다.
int count = numbers.Count;
Console.WriteLine(count); // 2
}
}
위 코드는 다음과 같은 결과를 출력합니다.
true
1
3
2
결론
HashSet<T>는 중복되지 않는 요소를 저장하는 효율적인 컬렉션입니다. HashSet<T>는 해시 테이블을 사용하여 요소를 저장하기 때문에, 요소를 빠르게 검색할 수 있습니다.
728x90
'C#' 카테고리의 다른 글
C#의 정적 타입 정보 연산자 (0) | 2023.10.26 |
---|---|
C# 람다 식 : 캡처 (0) | 2023.10.20 |
C#의 char 자료형 (0) | 2023.10.18 |
코드 실행시간 측정 : Stopwatch (2) | 2023.10.17 |
C#에서 입출력을 다루는 방법 (0) | 2023.10.13 |