Ste*_*gas 279 c# collections hashset addrange
使用列表,您可以:
list.AddRange(otherCollection);
Run Code Online (Sandbox Code Playgroud)
HashSet中没有添加范围方法.将另一个集合添加到HashSet的最佳方法是什么?
您还可以将CONCAT与 LINQ 结合使用。这会将一个集合或特别是一个附加HashSet<T>
到另一个集合上。
var A = new HashSet<int>() { 1, 2, 3 }; // contents of HashSet \'A\'\n var B = new HashSet<int>() { 4, 5 }; // contents of HashSet \'B\'\n\n // Concat \'B\' to \'A\'\n A = A.Concat(B).ToHashSet(); // Or one could use: ToList(), ToArray(), ...\n\n // \'A\' now also includes contents of \'B\'\n Console.WriteLine(A);\n >>>> {1, 2, 3, 4, 5}\n
Run Code Online (Sandbox Code Playgroud)\n注意: Concat()
创建一个全新的集合。而且,UnionWith()
比 Concat() 更快。
“ ...这个 ( Concat()
) 还假设您实际上有权访问引用哈希集的变量并允许对其进行修改,但情况并非总是如此。 ” \xe2\x80\x93 @PeterDuniho
这是一种方法:
public static class Extensions
{
public static bool AddRange<T>(this HashSet<T> source, IEnumerable<T> items)
{
bool allAdded = true;
foreach (T item in items)
{
allAdded &= source.Add(item);
}
return allAdded;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
62658 次 |
最近记录: |