Sets in the C# refer to the HashSet. It is an unordered collection of unique elements. It refers to the System.Collections.Generic namespace. Mainly it is used when we want to remove the duplicate elements from being inserted in the list. Following is the declaration of the HashSet:
Syntax:
var set = new HashSet<string>(arr1);
To remove the duplicate elements, it is going to be set into an array.
Syntax:
string[] arr2 = set.ToArray();
Difference between List and Set:
S.No. | Basis | List | Set |
---|---|---|---|
1. | Define | The List is a type of data structure to store the elements. | Sets are also a type of data structure but to stores the unique elements. |
2. | Sequence | A sequence of the elements is important. | The sequence doesn’t matter, it only depends upon the implementation. |
3. | Elements Access | Elements in the lists are accessed by using the indices of the elements in the list. | In the set, elements are the indices that can be easily accessible. |
4. | Interface | Systems.Collection.IList is the Interface available for the List Implementation. | Systems.Collection.ISet is the Interface available for the Set Implementation. |
5. | Implementation | It can be implemented using two ways:
| It can also be implemented using two ways:
|
6. | Duplicity | The list can have duplicate elements. | Set contains only unique elements. |
7. | Performance | List performance is not as good as Set. | Sets have good performance than List. |
8. | Methods | There are many methods available to apply on the List. Some of them are as :
| There are many methods available to apply on Set. Some of them are as :
|