在C#中,要将HashSet转换为其他类型,您需要创建一个新的集合对象并将HashSet中的元素添加到新集合中。以下是一些常见的集合类型转换示例:
- 将HashSet
转换为List :
HashSethashSet = new HashSet { 1, 2, 3, 4, 5 }; List list = hashSet.ToList();
- 将HashSet
转换为List :
HashSethashSet = new HashSet { "apple", "banana", "cherry" }; List list = hashSet.ToList();
- 将HashSet
转换为HashSet:
HashSethashSet1 = new HashSet { 1, 2, 3, 4, 5 }; HashSet hashSet2 = new HashSet (hashSet1);
- 将HashSet
转换为SortedSet :
HashSethashSet = new HashSet { 1, 2, 3, 4, 5 }; SortedSet sortedSet = new SortedSet (hashSet);
请注意,这些示例中的转换不会修改原始HashSet。如果您想要修改原始HashSet,请使用相应的集合方法(如CopyTo()
或UnionWith()
)将元素添加到新集合中。