本文整理汇总了C#中System.Collections.Generic.HashSet<T>类的典型用法代码示例。如果您正苦于以下问题:C# HashSet<T>类的具体用法?C# HashSet<T>怎么用?C# HashSet<T>使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HashSet<T>类属于System.Collections.Generic命名空间,在下文中一共展示了HashSet<T>类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: for
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
void DisplaySet(HashSet<int> collection)
{
Console.Write("{");
foreach (int i in collection)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
输出:
* evenNumbers contains 5 elements: { 0 2 4 6 8 } * oddNumbers contains 5 elements: { 1 3 5 7 9 } * numbers UnionWith oddNumbers... * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }