Tuesday, August 16, 2022

Sets example in c#

 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.BasisListSet
1.DefineThe 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.SequenceA sequence of the elements is important.The sequence doesn’t matter, it only depends upon the implementation.
3.Elements AccessElements 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:

  • Static List ( using Array )
  • Dynamic List ( using LinkedList )

It can also be implemented using two ways:

  • HashSet ( Hashtable )
  • Sorted Set ( Red Black Tree-based )
6. Duplicity The list can have duplicate elements.Set contains only unique elements.
7. PerformanceList 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 :

  • int Add(element)
  • void Insert(int, element)
  • void Clear()
  • int IndexOf(element)

There are many methods available to apply on Set. Some of them are as :

  • bool Add(element)
  • bool Contains(element)
  • bool Remove(element)
  • void Clear()