三默网为您带来有关“C#基础——Hashset类”的文章内容,供您阅读参考。

C#基础——Hashset类

2023-01-21 19:54:27

C#基础——Hashset类

本文讲述了C#基础——Hashset类!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

HashSet基础概念:

HashSet 是 System.Collections.Generic 命名空间下的 HashSet<T> 类,是一个高性能且无序的集合。

因为HashSet是无序的,所以它既不能做排序操作,又不能像数组那样索引。在 HashSet 上只能使用foreach来进行迭代,而无法使用for循环。

HashSet中的元素不重复(可以存放单一的null),即具有元素唯一性,若向 HashSet 中插入重复元素,其内部会忽视此次操作,不会报出异常。因此若想拥有一个具有唯一值的集合,HashSet将会是一个具有超高效检索性能的极佳选择(例子:见Leecode刷题第三题)。

static void Main(string[] args)

        {

            HashSet<string> hashSet = new HashSet<string>();

            hashSet.Add("A");

            hashSet.Add("B");

            hashSet.Add("C");

            hashSet.Add("D");

            hashSet.Add("D");

            Console.WriteLine("The number of elements is: {0}", hashSet.Count);

            Console.ReadKey();

        }

例如上述这段代码的输出结果就是:ABCD,最后一个重复的D被忽略了。

HashSet的一些常用方法:

1)在HashSet中查找是否含有某元素:Contains方法

示例:

hashSet.Contains("D")

2)在HashSet中移除某元素:Remove 方法

示例:

hashSet.Remove(item);

3)删除 HashSet 中的所有元素: Clear 方法

HashSet对于集合Set的一些操作:

4)判断 HashSet 是否为某一个集合的完全子集:IsProperSubsetOf方法

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D" };

HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X" };

HashSet<string> setC = new HashSet<string>() { "A", "B", "C", "D", "E" };

if (setA.IsProperSubsetOf(setC)) //是子集输出1,不是输出0

   Console.WriteLine("setC contains all elements of setA.");

if (!setA.IsProperSubsetOf(setB))

   Console.WriteLine("setB does not contains all elements of setA.");

5)集合的合并:UnionWith方法

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };

HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };

setA.UnionWith(setB);

foreach(string str in setA)

{

   Console.WriteLine(str);

}

//最终setA的输出结果是ABCDEXY

最终setA会输出setA和setB中的所有元素

6)两个 HashSet 的交集:IntersectWith 方法

setA.IntersectWith(setB);

输出结果是setA和setB集合中都有的元素

7)集合减,时间复杂度是 O(N):ExceptWith 方法

setA.ExceptWith(setB);

输出setA集合中有但setB集合中没有的元素

8)两个集合都不全有的元素:SymmetricExceptWith 方法

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };

HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };

setA.SymmetricExceptWith(setB);

foreach (string str in setA)

{

  Console.WriteLine(str);

}

//对于这个示例,最终输出结果是BDEXY

想高效系统的学习Python编程语言,推荐大家关注一个公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

C#基础——Hashset类