C# HashSet 计算学习笔记

C# HashSet 学习笔记

写在前面

*HashSet是一个相对“冷门”的类型,平时在项目中用得不多,但是在特定的业务中可以大用。*

先来了解下HashSet类,主要被设计用来存储集合,做高性能集运算,例如两个集合求交集、并集、差集等。从名称可以看出,它是基于Hash的,可以简单理解为没有Value的Dictionary。

HashSet不能用索引访问,不能存储重复数据,元素T必须正确实现了EqualsGetHashCode

HashSet的一些特性如下:

  1. HashSet中的值不能重复且没有顺序。
  2. HashSet的容量会按需自动添加。

集合运算

IntersectWith(IEnumerable other)(交集)

/*
 * IntersectWith(IEnumerable other)(交集)
 * 这个的意思就是将两个集的数据相交的数据
 * 只有在这两个数据相交的情况下才可以通过判断。
 */
HashSet<int> set1 = new HashSet<int>() {1,2,3};
HashSet<int> set2 = new HashSet<int>() { 2, 3, 4 };

set1.IntersectWith(set2);

foreach (var item in set1)
    Console.WriteLine(item);

Console.ReadKey(true);

最后的输出结果为:

image-20200522102724647

image-20200522103611562

这个就是结合中 使用交集的大概运算过程。

UnionWity(IEnumerable other)(并集)

/*
 * UnionWith(IEnumberable other)(并集)
 * 并集的意思就是将两个集中的数据合并起来。
 * 但是之合并集中没有的数据,如果当前被合并的元素在集中已经存在,那么就将跳过不合并
 * 
 */
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 2, 3, 4 };
set1.UnionWith(set2);

foreach (var item in set1)
{
    Console.WriteLine(item);
}
Console.ReadKey();

这里就是我们的并集操作的代码了。

看看运行效果:

image-20200522104449177

ExceptWith(IEnumberable other)(排除)

/*
 * ExceptWith(IEnumberable other)(排除)
 * 这里对于集的排除操作就是,也就是将我们的set1 和 我们的 set2去做对比
 * 如果在set1中存在的元素set2中也存在那么我们就将排除
 * 如果set1中元素在set2中没有,我们就将该元素保存
 * 
 */
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 2, 3, 4 };
set1.ExceptWith(set2);
foreach (var item in set1)
{
    Console.WriteLine(item);
}
Console.ReadKey(true);

这部分其实就是我们的排除操作的代码了。

看看我们的运行效果:

image-202005q22105415064

因为在set1集中有1、2、3这三个元素,然后再set2中有2、3、4这三个元素。因为set1中的2、3和set2中的元素重合和,将会被排除。所以这两个集通过使用排出后只有1这一个元素了。

posted @ 2020-05-22 11:04  GreatCoder726  阅读(324)  评论(0编辑  收藏  举报