リストを使用すると、次のことができます。
list.AddRange(otherCollection);
に範囲の追加メソッドはありませんHashSet
。ICollection
に別のものを追加するための最良の方法は何HashSet
ですか?
リストを使用すると、次のことができます。
list.AddRange(otherCollection);
に範囲の追加メソッドはありませんHashSet
。ICollection
に別のものを追加するための最良の方法は何HashSet
ですか?
の場合HashSet<T>
、名前はUnionWith
です。
これは、HashSet
動作の明確な方法を示すためです。Add
のようにランダムな要素のセットを安全に設定することはできませんCollections
。一部の要素は自然に蒸発する可能性があります。
UnionWith
それは「他との融合」にちなんで名付けられたと思いますがHashSet
、過負荷もありIEnumerable<T>
ます。
これは1つの方法です。
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;
}
}
LINQでCONCATを使用することもできます。これにより、コレクションまたは具体的には別のコレクションが追加されますHashSet<T>
。
var A = new HashSet<int>() { 1, 2, 3 }; // contents of HashSet 'A'
var B = new HashSet<int>() { 4, 5 }; // contents of HashSet 'B'
// Concat 'B' to 'A'
A = A.Concat(B).ToHashSet(); // Or one could use: ToList(), ToArray(), ...
// 'A' now also includes contents of 'B'
Console.WriteLine(A);
>>>> {1, 2, 3, 4, 5}
注: Concat()
まったく新しいコレクションを作成します。また、UnionWith()
Concat()よりも高速です。
" ... this(Concat()
)は、ハッシュセットを参照する変数に実際にアクセスでき、それを変更できることも前提としていますが、常にそうであるとは限りません。 " – @PeterDuniho