Za pomocą listy możesz:
list.AddRange(otherCollection);
W HashSet nie ma metody dodawania zakresu . Jaki jest najlepszy sposób na dodanie kolejnej kolekcji do HashSet?
Za pomocą listy możesz:
list.AddRange(otherCollection);
W HashSet nie ma metody dodawania zakresu . Jaki jest najlepszy sposób na dodanie kolejnej kolekcji do HashSet?
Odpowiedzi:
Bo HashSet<T>nazwa to UnionWith.
Ma to na celu wskazanie odrębnego sposobu HashSetdziałania. Nie możesz bezpiecznie Addzestaw losowych elementów, jak w Collectionsniektórych, niektóre elementy mogą naturalnie wyparować.
Myślę, że UnionWithbierze to swoją nazwę po „połączeniu z innym HashSet”, ale jest też przeciążenie IEnumerable<T>.
To jest jeden sposób:
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;
}
}
HashSet(iISet) został stworzony z matematycznie ustalonym terminem.UnionWithbył bliższym terminem. Z wyjątkiemExcept, które wyraźnie należy nazwaćSubtractmatematycznie.