问题描述
当我组合2个哈希集时,HashSet.Union
与HashSet.Unionwith
之间的区别是什么.
What the difference between HashSet.Union
vs HashSet.Unionwith
when i combine 2 hashsets.
我正试图像这样组合:
HashSet<EngineType> enginesSupportAll = _filePolicyEvaluation.EnginesSupportAll;
enginesSupportAll = enginesSupportAll != null ? new HashSet<EngineType>(engines.Union(enginesSupportAll)) : enginesSupportAll;
此示例的最佳方法是什么?为什么?
what is the best method for this example and why?
推荐答案
好吧,它不是HashSet.Union
,而是 Enumerable.Union
,因此您使用的LINQ扩展方法可与任何IEnumerable<>
类型配合使用,而 HashSet.UnionWith
是真正的HashSet
方法,用于修改当前实例.
Well, it's not HashSet.Union
but Enumerable.Union
, so you are using a LINQ extension method that works with any kind of IEnumerable<>
whereas HashSet.UnionWith
is a real HashSet
method that modifes the current instance.
-
Union
返回IEnumerable<TSource>
-
UnionWith
是void
,它修改了当前的HashSet
实例 - 也许
UnionWith
效率更高,因为可以对其进行优化
Union
returns anIEnumerable<TSource>
UnionWith
isvoid
, it modifies the currentHashSet
instance- maybe
UnionWith
is slightly more efficient because it can be optimized
如果您不想在方法中支持任何类型的序列,因此HashSet
已修复并且可以对其进行修改,请使用该序列,否则请使用LINQ扩展.如果您仅出于此目的创建HashSet
实例,那并不重要,我希望LINQ更加灵活并能够链接我的查询.
If you don't want to support any kind of sequence in your method so HashSet
is fix and you can modify it, use that, otherwise use the LINQ extension.If you create the HashSet
instance just for this purpose it doesn't really matter and i would prefer LINQ to be more flexible and to be able to chain my query.
这篇关于HashSet中的Union vs Unionwith的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!