[What is] the difference between HashSet
and List in .NET?
A List in C# is a collection of items that are stored in order, and can be accessed by an index. Lists allow for duplicate items and have a variety of built-in methods for adding, removing, and searching for items.
A HashSet, on the other hand, is a collection of items that does not have a specific order, and does not allow for duplicate items. It uses a data structure called a hash table to store items, which allows for fast lookups and insertions.
Here is an example of how you might use a List and a HashSet in C#:
// Create a List of integers List
myList = new List (); myList.Add(1); myList.Add(2); myList.Add(3); myList.Add(3); // duplicate item allowed // Create a HashSet of integers HashSet myHashSet = new HashSet (); myHashSet.Add(1); myHashSet.Add(2); myHashSet.Add(3); myHashSet.Add(3); // duplicate item not allowed
In this example, we created a List of integers and added four items to it. Because Lists allow for duplicate items, the number 3 is added twice. We then created a HashSet of integers and added the same four items to it. Because HashSets do not allow for duplicate items, the second occurrence of the number 3 is not added to the collection.
You could access the items in a List by their index, for example:
//retrieve the first element int firstListElem = myList;
You could also use HashSet’s method like Contains to check if an item exist in the HashSet.
//check if the element 2 is in the HashSet bool isInHashSet = myHashSet.Contains(2);
In summary, Lists are ordered collections that allow duplicate items, while HashSets are unordered collections that do not allow duplicate items. Lists are good when you need a collection that preserves the order of the items and allows duplicates, while HashSets are good when you need a collection that does not preserve order and does not allow duplicates.