什么是 HashSet?C# 中的 Set 集合是什么?
csharpprogrammingserver side programming更新于 2025/10/13 12:52:17
C# 中的 HashSet 可以消除数组中重复的字符串或元素。在 C# 中,它是一个优化的 Set 集合。
让我们看一个使用 C# HashSet 减号删除重复字符串的示例。
示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
string[] arr1 = {
"one",
"two",
"two",
"one",
"three"
};
Console.WriteLine(string.Join(",", arr1));
// HashSet
var h = new HashSet(arr1);
// 消除重复的单词
string[] arr2 = h.ToArray();
Console.WriteLine(string.Join(",", arr2));
}
}
声明 HashSet。
var h = new HashSet<string7gt;(arr1);
现在将其设置在数组上以删除重复的单词 −
string[] arr2 = h.ToArray();

