>  기사  >  백엔드 개발  >  C# 해시테이블

C# 해시테이블

WBOY
WBOY원래의
2024-09-03 15:04:59383검색

C#의 해시테이블은 키-값 쌍 형태의 데이터 모음으로, 키의 해시 코드를 기반으로 하며 키는 컬렉션 내의 요소나 데이터에 액세스하는 데 사용됩니다. 이는 객체 클래스에서 해시테이블로 상속됩니다. 따라서 기본적으로 C# 또는 모든 프로그래밍 언어의 해시테이블은 해시 코드 형식으로 적절하게 구성된 키와 값 쌍의 간단한 표현입니다.

구문:

이제 C# 해시테이블이 무엇인지 알았으니 해시테이블의 올바른 구현을 위한 표준 구문을 이해해 보겠습니다. 다음은 프로그램에서 해시테이블을 사용하기 위한 표준 구문과 필수 시스템 파일입니다.

using System.Collections;
Hashtableht = new Hashtable();

컬렉션이 포함된 시스템 파일은 해시테이블에서 사용하는 필수 기능과 메서드를 가져오는 역할을 합니다. 그런 다음 해시 테이블이 여기서 주요 키워드이고 ht로 인스턴스를 생성했으며 새로 생성된 ht에 대해 작업이 수행됩니다. 이제 해시테이블 구현을 위한 올바른 구문을 알았으니 작동 방식을 이해해 보겠습니다.

C#에서 Hashtable은 어떻게 작동하나요?

앞서 설명했듯이 해시테이블은 키-값 쌍 형태의 데이터 또는 정보 모음이라는 것을 알고 있습니다. 키 값 쌍의 간단한 예는 "Name: Sulaksh"입니다. 여기서 키는 Name이고 값은 Sulaksh입니다. 키는 동일하게 유지되지만 값은 다를 수 있습니다. 해시테이블은 키(key)와 값(value)으로 구성되며, 이를 중괄호로 표현하고 해시함수를 사용하여 계산합니다.

이제 해시테이블을 올바르게 구현하고 예제 작업을 이해해 보겠습니다.

C# 해시테이블의 예

첫 번째 예는 숫자 키와 값이 포함된 간단한 해시테이블이 있고 해시테이블에 있는 전체 요소 수를 인쇄하는 해시테이블의 간단한 구현입니다. 코드는 다음과 같습니다.

예시 #1

코드:

using System;
using System.Collections;
class sampleht {
static public void Main() {
Hashtableexampleht = new Hashtable();
exampleht.Add(1, " Element 1");
exampleht.Add(2, " Element 2");
exampleht.Add(3, " Element 3");
Console.WriteLine("\n The Total No. of elements: {0}", exampleht.Count);
}
}

코드 설명: 시스템 파일로 시작하고 여기서는 컬렉션이 가장 중요하며 그 다음에는 클래스가 있고 그 안에 주요 메소드가 있습니다. 기본 메소드 내에는 해시테이블 선언과 ​​세 개의 키-값 쌍이 있습니다. 요소를 삽입하는 추가 기능을 구현했습니다. 따라서 해시테이블은 세 개의 키-값 쌍으로 구성되며 마지막으로 해시테이블 내에 있는 총 요소 수인 3개를 인쇄하는 print 문이 있습니다. 여기서는 간단한 카운트 기능을 사용하고 있습니다. 출력은 아래 첨부된 스크린샷을 참조하세요.

C# 해시테이블

예상대로 출력에는 해시 테이블에 4개의 요소가 있다고 나와 있습니다. 이제 다음 예로 넘어가서 해시 테이블의 키와 값을 표시해 보겠습니다.

예시 #2

코드:

using System;
using System.Collections;
class exampleHT {
static publicvoid Main() {
HashtablesampleHT = new Hashtable();
sampleHT.Add(1, " One");
sampleHT.Add(2, " Two");
sampleHT.Add(3, " Three");
Console.WriteLine("\n Below is the content of Hashtable: \n");
foreach (DictionaryEntry entry in sampleHT) {
Console.WriteLine(" {0}, {1}", entry.Key, entry.Value);
}
}
}

코드 설명: 앞선 예와 유사하게 시스템 파일과 클래스 안에 기본 메소드가 있습니다. 그런 다음 해시 테이블이 있고 그 뒤에 키 값 쌍이 있고 그 다음에는 print 문이 있습니다. 그런 다음 한 번에 하나의 요소를 선택하고 다음 줄에서 이를 출력으로 인쇄하는 foreach 문이 있습니다. 우리의 출력은 키와 값 형태의 요소 목록이 될 것으로 예상됩니다. 아래 스크린샷을 참조하세요.

C# 해시테이블

예상대로 출력은 해시테이블의 요소를 인쇄하고 이제 다음 예에서는 outhashtable을 사용하여 지우기 기능을 구현하며 코드는 다음과 같습니다.

예시 #3

코드:

using System;
using System.Collections;
class sampleht {
static public void Main()  {
Hashtableexampleht = new Hashtable();
exampleht.Add(1, " Element 1");
exampleht.Add(2, " Element 2");
exampleht.Add(3, " Element 3");
Console.WriteLine("\n Elements of the Hashtable :");
foreach(DictionaryEntry ele1 in exampleht) {
Console.WriteLine(ele1.Value);
}
Console.WriteLine(" No. of elements before clearing: {0} ", exampleht.Count);
exampleht.Clear();
Console.WriteLine(" Total No. of elements now: {0} ", exampleht.Count);
}
}

코드 설명: 필수 시스템 파일과 메소드를 사용하여 해시 테이블과 총 3개의 키 값 쌍이 정의되어 있습니다. 해시테이블에 요소를 추가하기 위해 add 함수를 구현했습니다. 그런 다음 해시테이블 내의 모든 요소인 3개를 간단히 인쇄하는 print 문을 실행합니다. 해시테이블을 지우기 전에 목록에 있는 전체 요소 수를 인쇄한 다음 전체 해시테이블을 지우는 명확한 함수를 사용합니다. 즉, 모든 요소가 목록에서 지워지고 최종 인쇄 문에서 숫자를 인쇄합니다. 현재 존재하는 요소 수는 0이 됩니다.

C# 해시테이블

설명했듯이 삭제 기능이 작동하며 목록이 지워지고 이제 다음 예에서는 삭제 기능을 구현하겠습니다.

예시 #4

코드:

using System;
using System.Collections;
class sampleht {
static public void Main() {
Hashtableexampleht = new Hashtable();
exampleht.Add(1, " Element 1");
exampleht.Add(2, " Element 2");
exampleht.Add(3, " Element 3");
Console.WriteLine("\n List of Original Elements:");
foreach (var key in exampleht.Keys )
Console.WriteLine(" {0}, {1}",key , exampleht[key]);
exampleht.Remove(3);
exampleht.Remove(1);
Console.WriteLine("\n Elements after removal:");
foreach (var key in exampleht.Keys )
Console.WriteLine(" {0}, {1}",key , exampleht[key]);
}
}

Code Explanation: Just as our earlier examples, we have our system files, class, and the main method. Then we have our hashtable with a total of three key values. Then we have our print statement, which will print out the original list along with key and values, using foreach. We then have the remove function for two keys, which will remove the keys that we pass, then we have our print statement, which will use foreach and print every single element present in the hashtable after removing.

C# 해시테이블

Advantages

Advantages of any function or methodology is important to understand its real time applications and hashtable’s most widely known advantage is how it allows the developer the ability for synchronization. Hashtable has noted advantages over the search tree and this makes them practical to use in real time computer applications and for the purpose of database indexing. Speed, compared to other table type data structures is best delivered by hashtables. Having key value pairs makes it easy to anticipate the format regarding data and restructuring is done easily.

Conclusion

Hashtable in C# is a collection of elements, represented in a key value pair format. The key can be the same, while values differ and the key cannot be null while a value can be. We implemented an example of functions like remove, clear, and print. Hashtable has a speed advantage over other data structures.

위 내용은 C# 해시테이블의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# 대기다음 기사:C# 대기