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

————————————————
版权声明:本文为CSDN博主「一线码农」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/huangxinchen520/article/details/111477946

例如上述这段代码的输出结果就是: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
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值