📜  C#中List和Set的区别

📅  最后修改于: 2022-05-13 01:54:47.464000             🧑  作者: Mango

C#中List和Set的区别

该列表是 C# 与Java中的列表相同。基本上,它是一种可以存储变量的对象。但与对象不同的是,它仅按特定顺序存储变量。以下是我们可以声明变量的语法:

句法:

List numbers = new List();

列表和数组之间的区别在于列表的大小是动态的。另一方面,我们必须定义数组的大小。列表的初始化如下:

句法:

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

C# 中的集合指的是 HashSet。它是独特元素的无序集合。它指的是 System.Collections.Generic 命名空间。主要用于当我们想要删除重复元素插入到列表中时。以下是 HashSet 的声明:

句法:

var set = new HashSet(arr1);

要删除重复的元素,它将被设置为一个数组。

句法:

string[] arr2 = set.ToArray();

列表和集合的区别:

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