Open In App

Difference Between List and Set in C#

Last Updated : 02 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The list is C# is the same as the list in JAVA. Basically, it is a type of object which can store variables. But in difference with objects, it stores the variables only in a specific order. Following is the syntax from which we can declare variables:

Syntax:

List<int> numbers = new List<int>();

The difference between a list and an array is that lists are dynamic in size. On the other hand, we have to define the size of the array. The initialization of the list is as follows:

Syntax:

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

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:

  • 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.  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 :

  • 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()

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads