c# 遍历hashset
时间: 2023-11-17 22:59:01 浏览: 56
在C#中,遍历HashSet可以使用foreach循环或者迭代器。具体实现方法如下:
1.使用foreach循环遍历HashSet:
```
HashSet<string> hashSet = new HashSet<string>();
//向HashSet中添加元素
hashSet.Add("a");
hashSet.Add("b");
hashSet.Add("c");
//使用foreach循环遍历HashSet
foreach (string str in hashSet)
{
Console.WriteLine(str);
}
```
2.使用迭代器遍历HashSet:
```
HashSet<string> hashSet = new HashSet<string>();
//向HashSet中添加元素
hashSet.Add("a");
hashSet.Add("b");
hashSet.Add("c");
//使用迭代器遍历HashSet
IEnumerator<string> enumerator = hashSet.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
```
需要注意的是,在遍历HashSet时,元素的顺序是不确定的,因为HashSet是按照Hash算法来存储元素的。
相关问题
c#的hashset
C#中的HashSet是一种集合类型,它提供了高效的插入、删除和查找操作。HashSet中的元素是唯一的,不允许重复。以下是一个示例:
```csharp
// 创建一个HashSet
HashSet<string> hashSet = new HashSet<string>();
// 添加元素
hashSet.Add("apple");
hashSet.Add("banana");
hashSet.Add("orange");
// 删除元素
hashSet.Remove("banana");
// 查找元素
bool contains = hashSet.Contains("orange");
// 遍历HashSet
foreach (string item in hashSet)
{
Console.WriteLine(item);
}
// 对两个HashSet执行对称差异操作
HashSet<string> hSetN2 = new HashSet<string>();
hSetN2.Add("mahesh");
HashSet<string> hSetN4 = new HashSet<string>();
hSetN4.Add("mahesh");
hSetN4.SymmetricExceptWith(hSetN2);
```
c# hashset
C#中的HashSet是一种集合类型,它存储不重复的元素,并且可以进行高效的插入、删除和查找操作。HashSet基于哈希表实现,因此查找操作的性能非常高效。
要使用HashSet,首先需要引入System.Collections.Generic命名空间。然后,可以使用以下方式创建和操作HashSet:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个空的HashSet
HashSet<string> set1 = new HashSet<string>();
// 添加元素到HashSet
set1.Add("apple");
set1.Add("banana");
set1.Add("orange");
// 检查元素是否存在于HashSet中
bool containsApple = set1.Contains("apple");
Console.WriteLine($"HashSet contains apple: {containsApple}");
// 删除元素
bool removedBanana = set1.Remove("banana");
Console.WriteLine($"Removed banana: {removedBanana}");
// 遍历HashSet中的所有元素
foreach (string item in set1)
{
Console.WriteLine(item);
}
}
}
```
这是一个简单的示例,展示了如何创建一个HashSet、向其中添加元素、检查元素是否存在、删除元素以及遍历HashSet中的所有元素。希望这能回答你关于C#中HashSet的问题!如果还有其他问题,请随时提问。