哈希集的浅表副本 [英] Shallow copy of a hashset
本文介绍了哈希集的浅表副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
做这件事的最好方法是什么?
Whats the best way of doing it?
var set2 = new HashSet<reference_type>();
用这样的foreach遍历集合.
Traverse the set with a foreach like this.
foreach (var n in set)
set2.Add(n);
或者使用类似工会的东西.
Or use something like union like this.
set2 = set.UnionWith(set); // all the elements
推荐答案
使用构造函数:
HashSet<type> set2 = new HashSet<type>(set1);
我个人希望LINQ to Objects具有 ToHashSet
扩展方法,就像 List
和 Dictionary
一样.当然,创建自己的很容易:
Personally I wish LINQ to Objects had a ToHashSet
extension method as it does for List
and Dictionary
. It's easy to create your own of course:
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return new HashSet<T>(source);
}
(对于自定义相等比较器,还有其他重载.)
(With an other overload for a custom equality comparer.)
这使得创建匿名类型的集合变得容易.
This makes it easy to create sets of an anonymous type.
这篇关于哈希集的浅表副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文