C#|将元素添加到哈希集

A. 哈希集 是一个无序的 独特元素 .它属于 系统收藏。通用的 名称空间。它用于我们希望防止在集合中插入重复项的情况。就性能而言,它比列表要好。元素可以添加到 哈希集 使用 哈希集 .添加(T)方法 .

null

语法:

mySet.Add(T item);

在这里 迈塞特 是哈希集的名称。

参数:

项目: 要添加到集合中的元素。

返回类型: 此方法返回 符合事实的 如果元素被添加到 哈希集 对象 .如果元素已存在,则返回 错误的 .

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

例1:

// C# code to add element to HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of odd numbers
HashSet< int > odd = new HashSet< int >();
// Inserting elements in HashSet
for ( int i = 0; i < 5; i++) {
odd.Add(2 * i + 1);
}
// Displaying the elements in the HashSet
foreach ( int i in odd)
{
Console.WriteLine(i);
}
}
}


输出:

1
3
5
7
9

例2:

// C# code to add element to HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of strings
HashSet< string > mySet = new HashSet< string >();
// Inserting elements in HashSet
mySet.Add( "Geeks" );
mySet.Add( "GeeksforGeeks" );
mySet.Add( "GeeksClasses" );
mySet.Add( "GeeksQuiz" );
// Displaying the elements in the HashSet
foreach ( string i in mySet)
{
Console.WriteLine(i);
}
}
}


输出:

Geeks
GeeksforGeeks
GeeksClasses
GeeksQuiz

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享