Add SetItems ext fn for IImmutableSet/ImmutableHashSet

This commit is contained in:
John Colvin committed 2021-12-29 00:50:11 -05:00
1 parent 65304e6003
commit eacfd5c8fe
1 file changed
+40
@@ -82,5 +82,45 @@ namespace bts.collections {
}
return bd.ToImmutable();
}
public static IImmutableSet<T> SetItems<T>(this IImmutableSet<T> source, IEnumerable<T> values) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
if (values is null) {
throw new ArgumentNullException(nameof(values));
}
/// Prefer the <see cref="ImmutableHashSet{T}"/> implementation. It
/// uses an <see cref="ImmutableHashSet{T}.Builder"/> to remove
/// values, which is optimized for bulk changes (less memory
/// allocations, etc.).
if (source is ImmutableHashSet<T> ihs) {
return ihs.SetItems(values);
}
source = source.Clear();
foreach (var v in values) {
source = source.Add(v);
}
return source;
}
public static ImmutableHashSet<T> SetItems<T>(this ImmutableHashSet<T> source, IEnumerable<T> values) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
if (values is null) {
throw new ArgumentNullException(nameof(values));
}
var bd = source.ToBuilder();
bd.Clear();
foreach (var v in values) {
bd.Add(v);
}
return bd.ToImmutable();
}
}
}