• 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
     
  • 相关阅读:
    Markdown快捷笔记
    Linux常用命令
    Git使用
    HTML
    JavaScript-笔记2
    AngularJS-笔记2
    AngularJS-笔记1
    JQuery-笔记
    设置DataGridView的某个单元格为ComboBox
    记录文件浏览历史路径
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/16358623.html
Copyright © 2020-2023  润新知