课程: C# Algorithms

Hash-based structures in C# - C#教程

课程: C# Algorithms

Hash-based structures in C#

- [Instructor] Hash structures are great when working with collections, sets, and data formatted as key-value pairs. In C-sharp, there are a few different options we can use. First, there's the HashSet. The HashSet is a collection of unique items. It cannot contain duplicates, and unlike many of the tools we've used previously, the order of the items is not relevant. It's great if you need to keep track of a unique list of items. For example, let's say you're processing some purchases and you need to validate whether the vendor code is valid using a list of vendor codes. You could store the vendor codes with the HashSet. Then, quickly check if the code is valid in 01 time. C-sharp also has a dictionary type. This is especially useful if you need to work with key-value pairs. Let's say you have a series of employees and you need to look up information about a given employee using their ID. With a dictionary, you can store each employee value using the ID. Then, you can quickly look up an employee by their ID in constant time. If there's an identifier you can use to navigate your data, like an ID or a code, the dictionary type proves to be a very helpful tool in creating your algorithms. There is also the Hashtable type. This type is very similar to the dictionary type in that it stores key-value pairs, but there are a few differences in their implementations. The dictionary type is a generic collection while the Hashtable structure is not. With the Hashtable, there's no need to specify the type of key or value, but with the dictionary, those types are required. If you try to access a key that isn't present, the dictionary will give an error, but the Hashtable will just return null. The dictionary maintains the order of stored values while the Hashtable does not. The Hashtable is also thread safe while the dictionary is only thread safe for public static members. There are other differences between these types as well. Ultimately, the dictionary is often recommended because it adds type safety, eliminating the unboxing and reboxing of your data. Understanding the tools available to you is essential so you can choose the right one for your algorithm.

内容