📜  C#| HashSet中的元素数

📅  最后修改于: 2021-05-29 13:33:18             🧑  作者: Mango

HashSet是唯一元素的无序集合。在System.Collections.Generic命名空间中找到它。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。您可以使用HashSet .Count属性计算HashSet中的元素数量。

句法:

mySet.Count;

这里的mySet是HashSet

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to get the number of
// elements that are contained in HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet mySet = new HashSet();
  
        // Inserting elements in HashSet
        for (int i = 0; i < 5; i++) {
            mySet.Add(i * 2);
        }
  
        // To get the number of
        // elements that are contained in HashSet
        Console.WriteLine(mySet.Count);
    }
}
输出:
5

范例2:

// C# code to get the number of
// elements that are contained in HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet mySet = new HashSet();
  
        // To get the number of
        // elements that are contained in HashSet.
        // Note that, here the HashSet is empty
        Console.WriteLine(mySet.Count);
    }
}
输出:
0

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.hashset-1.count?view=netframework-4.7.2#System_Collections_Generic_HashSet_1_Count